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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code