Problem Description
A special typewriter has the lowercase English letters 'a' to 'z' arranged in a circle with a pointer initially at 'a'. At each second, you can either move the pointer one step clockwise or counterclockwise, or type the character at the current pointer position. Given a string word, determine the minimum number of seconds required to type it.
Key Insights
- The circle has 26 letters, so moving between letters can be done in either clockwise or counterclockwise direction.
- For any two characters, the minimum steps required is min(|pos2-pos1|, 26 - |pos2-pos1|).
- Typing each character always takes 1 second in addition to moving time.
- The problem can be solved by simulating the pointer movement from the starting character 'a' through each character in the word.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the word. Space Complexity: O(1).
Solution
We simulate the pointer moving on the circular typewriter. Start with the pointer at 'a'. For each character in the word, calculate the absolute difference between the current pointer position and the target character. Since the typewriter is circular, the effective distance is the minimum of the absolute difference and 26 minus that difference. Add this movement cost and 1 second for typing the character. Update the pointer and repeat until the word is fully typed.