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
.
For example:
word = "abc"
, the output is 5. The explanation is:
word = "bza"
, the output is 7.
word = "zjpc"
, the output is 34.What is the most efficient way to solve this problem? What is the time and space complexity of your solution? Can you identify any potential edge cases?
The simplest approach is to simulate the typewriter's movements and count the seconds. We start at 'a' and iterate through the word
. For each character, we calculate the distance to move clockwise and counterclockwise, choose the minimum, and add it to the total seconds. Finally, add one second for typing the character.
def min_seconds_naive(word):
current = 'a'
total_seconds = 0
for char in word:
diff = abs(ord(char) - ord(current))
move_seconds = min(diff, 26 - diff)
total_seconds += move_seconds + 1 # 1 for typing
current = char
return total_seconds
word
. We iterate through the word once.The optimal approach is essentially the same as the naive approach, as the core logic of calculating the minimum distance between characters is already optimal. The main improvement could involve minor code optimizations, but the underlying algorithm remains the same.
def min_seconds_optimal(word):
current = 'a'
total_seconds = 0
for char in word:
diff = abs(ord(char) - ord(current))
move_seconds = min(diff, 26 - diff)
total_seconds += move_seconds + 1
current = char
return total_seconds
word
.word
is empty, the function should return 0.def min_seconds(word):
if not word:
return 0
current = 'a'
total_seconds = 0
for char in word:
diff = abs(ord(char) - ord(current))
move_seconds = min(diff, 26 - diff)
total_seconds += move_seconds + 1
current = char
return total_seconds