Minimum Time to Type Word Using Special Typewriter - Problem

Imagine you have a circular typewriter where all 26 lowercase English letters 'a' to 'z' are arranged in a perfect circle, like numbers on a clock face! ๐Ÿ•

There's a pointer that starts at letter 'a' and can only type the character it's currently pointing to. The challenge? You need to type out an entire word, but first you must move the pointer to each required letter.

Movement Rules:

  • Each second, you can move the pointer one position clockwise or counterclockwise
  • Or you can type the current character the pointer is on
  • The letters wrap around: ...โ†’ y โ†’ z โ†’ a โ†’ b โ†’ ...

Goal: Given a string word, return the minimum number of seconds needed to type out all characters in the word.

Example: To type "bza", you'd move aโ†’b (1 sec), type 'b' (1 sec), move bโ†’aโ†’z (2 secs), type 'z' (1 sec), move zโ†’a (1 sec), type 'a' (1 sec) = 7 seconds total.

Input & Output

example_1.py โ€” Basic Movement
$ Input: word = "abc"
โ€บ Output: 5
๐Ÿ’ก Note: Start at 'a': type 'a' (1s) โ†’ move to 'b' (1s) โ†’ type 'b' (1s) โ†’ move to 'c' (1s) โ†’ type 'c' (1s) = 5 seconds total
example_2.py โ€” Wrapping Around
$ Input: word = "bza"
โ€บ Output: 7
๐Ÿ’ก Note: Start at 'a': move to 'b' (1s) โ†’ type 'b' (1s) โ†’ move to 'z' (2s, shorter to go backwards) โ†’ type 'z' (1s) โ†’ move to 'a' (1s) โ†’ type 'a' (1s) = 7 seconds
example_3.py โ€” Single Character
$ Input: word = "a"
โ€บ Output: 1
๐Ÿ’ก Note: Already at 'a', just type it (1 second)

Constraints

  • 1 โ‰ค word.length โ‰ค 100
  • word consists of lowercase English letters only
  • The pointer always starts at 'a'

Visualization

Tap to expand
abcdefghijklmnopqrstuvwxyzClockwise: 25 stepsCounterclockwise: 1 step โœ“
Understanding the Visualization
1
Position Mapping
Map each letter to position: a=0, b=1, ..., z=25
2
Distance Calculation
For any two positions, calculate clockwise and counterclockwise distances
3
Optimal Path
Choose the shorter path and add typing time (1 second)
4
Accumulate Time
Sum all movement and typing times for final answer
Key Takeaway
๐ŸŽฏ Key Insight: In a circular arrangement, there are always exactly two paths between any two points. The optimal solution always chooses the shorter arc, making this a simple greedy algorithm with O(n) time complexity.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.5K Views
Medium Frequency
~8 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