You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate.
For example, the letter 'A' is located at coordinate (0, 0), the letter 'B' is located at coordinate (0, 1), the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located at coordinate (4, 1).
Given the string word, return the minimum total distance to type such string using only two fingers.
The distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|.
Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.
Example 1:
Input: word = "CAKE"
Output: 3
Explanation: Using two fingers, one optimal way to type "CAKE" is:
Finger 1 on letter 'C' -> cost = 0
Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2
Finger 2 on letter 'K' -> cost = 0
Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1
Total distance = 3
Example 2:
Input: word = "HAPPY"
Output: 6
Explanation: Using two fingers, one optimal way to type "HAPPY" is:
Finger 1 on letter 'H' -> cost = 0
Finger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2
Finger 2 on letter 'P' -> cost = 0
Finger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0
Finger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4
Total distance = 6
Problem summary: You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate. For example, the letter 'A' is located at coordinate (0, 0), the letter 'B' is located at coordinate (0, 1), the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located at coordinate (4, 1). Given the string word, return the minimum total distance to type such string using only two fingers. The distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|. Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
"CAKE"
Example 2
"HAPPY"
Related Problems
Minimum Time to Type Word Using Special Typewriter (minimum-time-to-type-word-using-special-typewriter)
Step 02
Core Insight
What unlocks the optimal approach
Use dynamic programming.
dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1320: Minimum Distance to Type a Word Using Two Fingers
class Solution {
public int minimumDistance(String word) {
int n = word.length();
final int inf = 1 << 30;
int[][][] f = new int[n][26][26];
for (int[][] g : f) {
for (int[] h : g) {
Arrays.fill(h, inf);
}
}
for (int j = 0; j < 26; ++j) {
f[0][word.charAt(0) - 'A'][j] = 0;
f[0][j][word.charAt(0) - 'A'] = 0;
}
for (int i = 1; i < n; ++i) {
int a = word.charAt(i - 1) - 'A';
int b = word.charAt(i) - 'A';
int d = dist(a, b);
for (int j = 0; j < 26; ++j) {
f[i][b][j] = Math.min(f[i][b][j], f[i - 1][a][j] + d);
f[i][j][b] = Math.min(f[i][j][b], f[i - 1][j][a] + d);
if (j == a) {
for (int k = 0; k < 26; ++k) {
int t = dist(k, b);
f[i][b][j] = Math.min(f[i][b][j], f[i - 1][k][a] + t);
f[i][j][b] = Math.min(f[i][j][b], f[i - 1][a][k] + t);
}
}
}
}
int ans = inf;
for (int j = 0; j < 26; ++j) {
ans = Math.min(ans, f[n - 1][j][word.charAt(n - 1) - 'A']);
ans = Math.min(ans, f[n - 1][word.charAt(n - 1) - 'A'][j]);
}
return ans;
}
private int dist(int a, int b) {
int x1 = a / 6, y1 = a % 6;
int x2 = b / 6, y2 = b % 6;
return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}
}
// Accepted solution for LeetCode #1320: Minimum Distance to Type a Word Using Two Fingers
func minimumDistance(word string) int {
n := len(word)
f := make([][26][26]int, n)
const inf = 1 << 30
for i := range f {
for j := range f[i] {
for k := range f[i][j] {
f[i][j][k] = inf
}
}
}
for j := range f[0] {
f[0][word[0]-'A'][j] = 0
f[0][j][word[0]-'A'] = 0
}
dist := func(a, b int) int {
x1, y1 := a/6, a%6
x2, y2 := b/6, b%6
return abs(x1-x2) + abs(y1-y2)
}
for i := 1; i < n; i++ {
a, b := int(word[i-1]-'A'), int(word[i]-'A')
d := dist(a, b)
for j := 0; j < 26; j++ {
f[i][b][j] = min(f[i][b][j], f[i-1][a][j]+d)
f[i][j][b] = min(f[i][j][b], f[i-1][j][a]+d)
if j == a {
for k := 0; k < 26; k++ {
t := dist(k, b)
f[i][b][j] = min(f[i][b][j], f[i-1][k][a]+t)
f[i][j][b] = min(f[i][j][b], f[i-1][a][k]+t)
}
}
}
}
ans := inf
for j := 0; j < 26; j++ {
ans = min(ans, f[n-1][word[n-1]-'A'][j])
ans = min(ans, f[n-1][j][word[n-1]-'A'])
}
return ans
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #1320: Minimum Distance to Type a Word Using Two Fingers
class Solution:
def minimumDistance(self, word: str) -> int:
def dist(a: int, b: int) -> int:
x1, y1 = divmod(a, 6)
x2, y2 = divmod(b, 6)
return abs(x1 - x2) + abs(y1 - y2)
n = len(word)
f = [[[inf] * 26 for _ in range(26)] for _ in range(n)]
for j in range(26):
f[0][ord(word[0]) - ord('A')][j] = 0
f[0][j][ord(word[0]) - ord('A')] = 0
for i in range(1, n):
a, b = ord(word[i - 1]) - ord('A'), ord(word[i]) - ord('A')
d = dist(a, b)
for j in range(26):
f[i][b][j] = min(f[i][b][j], f[i - 1][a][j] + d)
f[i][j][b] = min(f[i][j][b], f[i - 1][j][a] + d)
if j == a:
for k in range(26):
t = dist(k, b)
f[i][b][j] = min(f[i][b][j], f[i - 1][k][a] + t)
f[i][j][b] = min(f[i][j][b], f[i - 1][a][k] + t)
a = min(f[n - 1][ord(word[-1]) - ord('A')])
b = min(f[n - 1][j][ord(word[-1]) - ord('A')] for j in range(26))
return int(min(a, b))
// Accepted solution for LeetCode #1320: Minimum Distance to Type a Word Using Two Fingers
struct Solution;
impl Solution {
fn minimum_distance(word: String) -> i32 {
let n = word.len();
let s: Vec<i32> = word.bytes().map(|b| (b - b'A') as i32).collect();
let mut memo: Vec<Vec<Vec<i32>>> = vec![vec![vec![-1; 27]; 27]; n];
Self::dp(0, 26, 26, &mut memo, &s, n)
}
fn dp(
start: usize,
f1: i32,
f2: i32,
memo: &mut Vec<Vec<Vec<i32>>>,
s: &[i32],
n: usize,
) -> i32 {
if start == n {
0
} else {
if memo[start][f1 as usize][f2 as usize] != -1 {
return memo[start][f1 as usize][f2 as usize];
}
let mut res = std::i32::MAX;
let g = s[start];
res = res.min(Self::dp(start + 1, g, f2, memo, s, n) + Self::dist(f1, g));
res = res.min(Self::dp(start + 1, f1, g, memo, s, n) + Self::dist(f2, g));
memo[start][f1 as usize][f2 as usize] = res;
res
}
}
fn dist(f: i32, g: i32) -> i32 {
if f == 26 {
0
} else {
(f / 6 - g / 6).abs() + (f % 6 - g % 6).abs()
}
}
}
#[test]
fn test() {
let word = "CAKE".to_string();
let res = 3;
assert_eq!(Solution::minimum_distance(word), res);
let word = "HAPPY".to_string();
let res = 6;
assert_eq!(Solution::minimum_distance(word), res);
let word = "NEW".to_string();
let res = 3;
assert_eq!(Solution::minimum_distance(word), res);
let word = "YEAR".to_string();
let res = 7;
assert_eq!(Solution::minimum_distance(word), res);
}
// Accepted solution for LeetCode #1320: Minimum Distance to Type a Word Using Two Fingers
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1320: Minimum Distance to Type a Word Using Two Fingers
// class Solution {
// public int minimumDistance(String word) {
// int n = word.length();
// final int inf = 1 << 30;
// int[][][] f = new int[n][26][26];
// for (int[][] g : f) {
// for (int[] h : g) {
// Arrays.fill(h, inf);
// }
// }
// for (int j = 0; j < 26; ++j) {
// f[0][word.charAt(0) - 'A'][j] = 0;
// f[0][j][word.charAt(0) - 'A'] = 0;
// }
// for (int i = 1; i < n; ++i) {
// int a = word.charAt(i - 1) - 'A';
// int b = word.charAt(i) - 'A';
// int d = dist(a, b);
// for (int j = 0; j < 26; ++j) {
// f[i][b][j] = Math.min(f[i][b][j], f[i - 1][a][j] + d);
// f[i][j][b] = Math.min(f[i][j][b], f[i - 1][j][a] + d);
// if (j == a) {
// for (int k = 0; k < 26; ++k) {
// int t = dist(k, b);
// f[i][b][j] = Math.min(f[i][b][j], f[i - 1][k][a] + t);
// f[i][j][b] = Math.min(f[i][j][b], f[i - 1][a][k] + t);
// }
// }
// }
// }
// int ans = inf;
// for (int j = 0; j < 26; ++j) {
// ans = Math.min(ans, f[n - 1][j][word.charAt(n - 1) - 'A']);
// ans = Math.min(ans, f[n - 1][word.charAt(n - 1) - 'A'][j]);
// }
// return ans;
// }
//
// private int dist(int a, int b) {
// int x1 = a / 6, y1 = a % 6;
// int x2 = b / 6, y2 = b % 6;
// return Math.abs(x1 - x2) + Math.abs(y1 - y2);
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × |\Sigma|^2)
Space
O(n × |\Sigma|^2)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.