Minimum Distance to Type a Word Using Two Fingers - Problem
Imagine you're a speed typist using a special QWERTY keyboard arranged in a grid layout. Each uppercase letter A-Z is positioned at specific coordinates on a 2D plane:
'A'is at(0,0)'B'is at(0,1)'P'is at(2,3)'Z'is at(4,1)
Here's the twist: you can only use TWO fingers to type! Your goal is to type a given word with the minimum total distance traveled by your fingers.
Distance calculation: Manhattan distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|
Special rules:
- Your fingers can start at any position for free (no initial cost)
- You don't have to start typing with the first letter immediately
- At each step, choose which finger to move to the next letter
Return: The minimum total distance to type the entire word.
Input & Output
example_1.py โ Basic word typing
$
Input:
word = "CAKE"
โบ
Output:
3
๐ก Note:
One optimal strategy: Start finger1 at 'C' (free), finger2 at 'A' (free). Move finger1 from 'C' to 'K' (distance=2), move finger2 from 'A' to 'E' (distance=1). Total: 0 + 0 + 2 + 1 = 3
example_2.py โ Single character
$
Input:
word = "HAPPY"
โบ
Output:
6
๐ก Note:
Start both fingers free. Place finger1 at 'H' (cost=0), move to 'A' (cost=3), place finger2 at 'P' (cost=0), move to another 'P' (cost=0), move finger1 to 'Y' (cost=3). Total: 0+3+0+0+3=6
example_3.py โ Edge case single letter
$
Input:
word = "NEW"
โบ
Output:
3
๐ก Note:
Start finger1 at 'N' (free), finger2 at 'E' (free), then move finger1 from 'N' to 'W' (distance=3). Total distance is 3.
Visualization
Tap to expand
Understanding the Visualization
1
Setup Grid
Letters A-Z arranged in 6ร5 grid, A at (0,0), Z at (4,1)
2
Initialize
Both fingers start free - can be placed anywhere at no cost
3
Choose Finger
For each letter, decide which finger to move based on minimum distance
4
Calculate Distance
Use Manhattan distance formula: |x1-x2| + |y1-y2|
Key Takeaway
๐ฏ Key Insight: Use dynamic programming to track optimal finger positions, taking advantage of free initial placement and making locally optimal decisions at each step.
Time & Space Complexity
Time Complexity
O(n * 26^2)
n letters ร 26 possible positions for finger1 ร 26 possible positions for finger2
โ Linear Growth
Space Complexity
O(n * 26^2)
Memoization table size plus recursion stack depth
โก Linearithmic Space
Constraints
- 2 โค word.length โค 300
- word consists of uppercase English letters only
- Each letter A-Z is positioned at coordinate ((ord(c) - ord('A')) // 6, (ord(c) - ord('A')) % 6)
- Initial finger positions are free (cost = 0)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code