We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Minimum Time to Type Word Using Special Typewriter

Difficulty: Easy


Problem Description

There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'. Each second, you may perform one of the following operations: move the pointer one character counterclockwise or clockwise, or type the character the pointer is currently on. Given a string word, return the minimum number of seconds to type out the characters in word.


Key Insights

  • The typewriter operates on a circular arrangement of the alphabet.
  • Moving the pointer can be done either counterclockwise or clockwise, and we should choose the shorter distance for efficiency.
  • Each character typing takes 1 second, so we must account for both move time and type time.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the word. Space Complexity: O(1), as we're using a constant amount of space for calculations.


Solution

To solve this problem, we can iterate through each character in the string and calculate the time needed to move the pointer from the current character to the next character. We can compute the distance in both directions (clockwise and counterclockwise) and take the minimum of the two. After calculating the move time, we add 1 second for typing the character. We'll maintain a total time counter that accumulates the seconds spent on both movements and typings.


Code Solutions

def minTimeToType(word: str) -> int:
    time = 0
    current_position = 'a'  # Pointer starts at 'a'
    
    for char in word:
        # Calculate clockwise and counterclockwise distances
        clockwise_distance = (ord(char) - ord(current_position)) % 26
        counterclockwise_distance = (ord(current_position) - ord(char)) % 26
        
        # Take the minimum distance to move
        time += min(clockwise_distance, counterclockwise_distance)
        
        # Move to the character and type it
        time += 1
        current_position = char  # Update the pointer position
    
    return time
← Back to All Questions