Skip to main content
Back to problems
#1320
Hard Algorithms

Minimum distance to type a word using two fingers

String Dynamic Programming
59.4% acceptance
Feb 25, 2026
1046
39
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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_distance(word: String) -> i32 {
    let w: Vec<usize> = word.bytes().map(|b| (b - b'A') as usize).collect();
    let n = w.len();

    let dist = |a: usize, b: usize| -> i32 {
      if a == 26 || b == 26 { return 0; }
      ((a / 6) as i32 - (b / 6) as i32).abs() + ((a % 6) as i32 - (b % 6) as i32).abs()
    };

    // dp[j] = min cost when one finger is at w[i] and other is at j (27 states: 0-25 + 26=none)
    const INF: i32 = i32::MAX / 2;
    let mut dp = vec![INF; 27];
    dp[26] = 0; // finger2 not placed, finger1 at w[0]

    for i in 0..n - 1 {
      let mut ndp = vec![INF; 27];
      for j in 0..27 {
        if dp[j] == INF { continue; }
        // Move finger1 (at w[i]) to w[i+1]
        let cost1 = dp[j] + dist(w[i], w[i+1]);
        if cost1 < ndp[j] { ndp[j] = cost1; }
        // Move finger2 (at j) to w[i+1]
        let cost2 = dp[j] + dist(j, w[i+1]);
        if cost2 < ndp[w[i]] { ndp[w[i]] = cost2; }
      }
      dp = ndp;
    }
    *dp.iter().min().unwrap()
  }
}