You are given a string word
consisting of lowercase English letters. You are typing on a special typewriter that only has lowercase English letters arranged in a circle, as shown in the figure below:
a <- b <- c
| |
v v
z -> y -> x
Each second, you may perform one of the following operations:
The initial position of the pointer is always at character ‘a’. Return the minimum number of seconds needed to type out the entire string word
.
word
be empty?
word
.def minTimeToType(word: str) -> int:
def get_distance(char1: str, char2: str) -> int:
pos1 = ord(char1) - ord('a')
pos2 = ord(char2) - ord('a')
clockwise_distance = (pos2 - pos1) % 26
counterclockwise_distance = (pos1 - pos2) % 26
return min(clockwise_distance, counterclockwise_distance)
total_time = 0
current_char = 'a'
for char in word:
move_time = get_distance(current_char, char)
total_time += move_time + 1 # +1 for typing the character
current_char = char
return total_time
# Example usage:
# word = "abc"
# print(minTimeToType(word)) # Output: 5
The time complexity for this solution is (O(n)), where (n) is the length of the string word
. This is because we are iterating over each character of the word exactly once and performing constant-time operations for each character.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?