Minimum Time to Type Word Using Special Typewriter - Problem

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.
  • 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.

Input & Output

Example 1 — Basic Case
$ Input: word = "abc"
Output: 5
💡 Note: Start at 'a': 0 seconds to move + 1 to type = 1 second. Move to 'b': 1 second + 1 to type = 2 seconds. Move to 'c': 1 second + 1 to type = 2 seconds. Total: 1 + 2 + 2 = 5 seconds.
Example 2 — Wraparound Case
$ Input: word = "bza"
Output: 7
💡 Note: Start at 'a', move to 'b': 1 + 1 = 2 seconds. Move to 'z': counterclockwise 1 step + 1 to type = 2 seconds. Move to 'a': clockwise 1 step + 1 to type = 2 seconds. Total: 2 + 2 + 2 = 6 seconds... Wait, let me recalculate: 'a' to 'b' = 1+1=2, 'b' to 'z' = min(24,2)=2, so 2+1=3, 'z' to 'a' = min(1,25)=1, so 1+1=2. Total = 2+3+2=7.
Example 3 — Single Character
$ Input: word = "a"
Output: 1
💡 Note: Already at 'a', so 0 seconds to move + 1 second to type = 1 second total.

Constraints

  • 1 ≤ word.length ≤ 100
  • word consists of lowercase English letters.

Visualization

Tap to expand
Minimum Time to Type Word Using Special Typewriter INPUT a b c d e f n ... z y x ... pointer word = "abc" Clockwise or Counter-clockwise ALGORITHM STEPS 1 Start at 'a' Type 'a': 1 sec 2 Move to 'b' 1 move + 1 type = 2 sec 3 Move to 'c' 1 move + 1 type = 2 sec 4 Calculate min path min(clockwise, counter) dist = min(|curr-next|, 26 - |curr-next|) a(1) --> b(2) --> c(2) Total: 1+2+2 = 5 FINAL RESULT a b c d e z ... Time Breakdown: Type 'a': 1 sec a-->b + type: 2 sec b-->c + type: 2 sec Output: 5 seconds Key Insight: For each character, choose the shorter path: min(clockwise distance, counterclockwise distance). With 26 letters in a circle, counterclockwise distance = 26 - clockwise distance. Add 1 second per character typed. TutorialsPoint - Minimum Time to Type Word Using Special Typewriter | Greedy Optimal Path Selection
Asked in
Google 15 Amazon 12 Microsoft 8
25.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen