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:
Given a string word
, return the minimum number of seconds to type out the characters in word
.
Example 1:
Input: word = "abc"
Output: 5
Example 2:
Input: word = "bza"
Output: 7
Example 3:
Input: word = "zjpc"
Output: 34
Constraints:
1 <= word.length <= 100
word
consists of lowercase English letters.def min_time_to_type(word: str) -> int:
"""Calculates the minimum time to type a word on a circular typewriter.
Args:
word: The word to type.
Returns:
The minimum number of seconds to type the word.
"""
current = 'a'
total_time = 0
for char in word:
diff = abs(ord(char) - ord(current))
move_time = min(diff, 26 - diff)
total_time += move_time + 1 # 1 second to type the character
current = char
return total_time
# Example Usage
word1 = "abc"
print(f"Input: {word1}, Output: {min_time_to_type(word1)}")
word2 = "bza"
print(f"Input: {word2}, Output: {min_time_to_type(word2)}")
word3 = "zjpc"
print(f"Input: {word3}, Output: {min_time_to_type(word3)}")
Initialization:
current = 'a'
: The pointer starts at 'a'.total_time = 0
: Initialize the total time taken.Iteration:
char
in the input word
.diff = abs(ord(char) - ord(current))
: Calculates the absolute difference between the ASCII values of the current character and the pointer's current position.move_time = min(diff, 26 - diff)
: Determines the minimum time to move the pointer to the required character. Since the characters are arranged in a circle, we take the minimum of the clockwise and counterclockwise distances.total_time += move_time + 1
: Adds the move_time
and 1 (for typing the character) to the total_time
.current = char
: Updates the pointer's current position to the character that was just typed.Return Value:
total_time
, which represents the minimum time required to type the entire word.Time Complexity: O(n)
Space Complexity: O(1)
current
, total_time
, diff
, and move_time
take up constant space.Empty Word:
Word with Same Characters:
move_time
might be 0 for some characters. The code handles this case correctly.Word with All 'a's:
Long Word:
Characters outside 'a' to 'z':