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:
7
💡 Note:
One optimal strategy: Start finger1 at 'C' (free), finger2 at 'A' (free). Move finger1 from 'C' to 'K' (distance=3), move finger2 from 'A' to 'E' (distance=4). Total: 0 + 0 + 3 + 4 = 7
example_2.py — Single character
$
Input:
word = "HAPPY"
›
Output:
8
💡 Note:
Start finger1 at 'H' (free), finger2 at 'A' (free). Move finger1 to 'P' (distance=2), move finger1 to 'P' (distance=0), move finger2 to 'Y' (distance=5). Total: 0+0+2+0+5=10. Alternative: finger1 at H->A->P->Y, finger2 at P costs 8.
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.
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)
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code