Talentd
FleetCode
Make and follow sheets.Sign in

Minimum Distance to Type a Word Using Two Fingers solution and explanation

HardDynamic ProgrammingString9 min read72.2% acceptanceUpdated 9 Apr 2026
Minimum Distance to Type a Word Using Two Fingers | Detailed | Intuition | Leetcode 1320 | MIKcodestorywithMIK · 46:35 · 7K viewsWatch on YouTube
9 more videos on this problem
  1. Minimum Distance to Type a Word Using Two Fingers | Detailed | Intuition | Leetcode 1320 | MIKcodestorywithMIK · 46:35 · 7K views
  2. Leetcode 1320: Minimum Distance to Type a Word Using Two FingersAlgorithms Casts · 24:05 · 3K views
  3. 5310 Minimum Distance to Type a Word Using Two FingersKelvin Chandra · 4:28 · 2K views
  4. LeetCode 1320. Minimum Distance to Type a Word Using Two FingersHappy Coding · 31:25 · 1K views
  5. leetcode 1320 | Minimum Distance to Type a Word Using Two Fingers | Recursion | DP | Leetcode POTDCode With Vick · 25:23 · 1K views
  6. 1320. Minimum Distance to Type a Word Using Two Fingers | Leetcode Daily - PythonLeetcode Daily · 6:19 · 1K views
  7. Minimum Distance to Type a Word using 2 Fingers | Hard | LeetCode 1320 | Best ExplainedAbhishek Jaiswal · 16:29 · 1K views
  8. Minimum Distance to Type a Word Using Two Fingers | LeetCode 1320 - Pythonimpoldev · 12:28 · 630 views
  9. Daily Leetcode #2203: Apr 12, 2026 - 1320. Minimum Distance to Type a Word Using Two FingersProgramming Live with Larry · 22:08 · 478 views
  10. Minimum Distance to Type a Word Using Two Fingers | Leetcode 1320 | Recursive + Memoization SolutionKernel Queen 👑 · 9:33 · 469 views

The problem

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

Constraints:

  • 2 <= word.length <= 300
  • word consists of uppercase English letters.

Approach overview

Problem Overview: You type a word using two fingers on a virtual keyboard containing the letters A–Z. Each move costs the Manhattan distance between keys. The goal is to minimize the total movement required to type the entire word.

Approach 1: Dynamic Programming with State Representation (O(n * 26 * 26) time, O(26 * 26) space)

Model the typing process with dynamic programming where the state represents the positions of both fingers. Use dp[i][f1][f2] or a compressed map where f1 and f2 store the characters currently under each finger while typing index i of the word. For every new character, choose which finger presses it and add the Manhattan distance between the previous key and the new key. The keyboard coordinates are computed from the character index (A=0 … Z=25) mapped onto a 6‑column grid. This brute-force DP checks all possible finger placements, ensuring the minimum cost is captured for each step.

Approach 2: Dynamic Programming with Two-dimensional Array (O(n * 26) time, O(26) space)

Observation: only one finger needs an explicit state. The other finger implicitly sits on the previously typed character. Maintain dp[x] where x represents the letter currently under the "free" finger while the other finger typed the last character. When processing the next letter, either move the active finger or switch to the free finger and update its position. This reduces the state space dramatically from 26×26 possibilities to just 26. Each transition computes the Manhattan distance between letters and updates the minimum movement cost.

Both approaches rely on precomputing keyboard coordinates and calculating distance using |r1-r2| + |c1-c2|. This problem is a classic application of dynamic programming combined with efficient state transitions over a string. The key insight is recognizing that the second finger can remain "free" until it becomes beneficial to move it.

Recommended for interviews: The optimized DP with a one‑finger state (O(n * 26)) is what most interviewers expect. The full state DP demonstrates correct reasoning about finger positions, but the reduced-state version shows stronger problem‑solving skills and the ability to simplify DP transitions.

Approach 1: Dynamic Programming with State Representation

This approach involves using a dynamic programming technique to keep track of the minimum cost for typing the word with two fingers. We define a function that returns the minimum cost to type from a given position with a specific state defined by finger positions.

The position of each character on the keyboard can be represented in terms of X and Y coordinates. Movements from character to character can thus be calculated using Manhattan distance.

We use a memoization technique to save previously computed states to avoid redundant calculations, ensuring efficiency.

def minimumDistance(word):
    def get_pos(ch):
        row = (ord(ch) - ord('A')) // 6
        col = (ord(ch) - ord('A')) % 6
        return (row, col)

    def dist(pos1, pos2):
        return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])

    n = len(word)
    dp = {}

    def dp_solve(i, f1, f2):
        if i == n:
            return 0
        if (i, f1, f2) in dp:
            return dp[(i, f1, f2)]
        pos_curr = get_pos(word[i])
        pos_f1 = get_pos(f1) if f1 else None
        pos_f2 = get_pos(f2) if f2 else None
        cost_f1 = dist(pos_f1, pos_curr) if pos_f1 else 0
        cost_f2 = dist(pos_f2, pos_curr) if pos_f2 else 0
        use_f1 = dp_solve(i + 1, word[i], f2) + cost_f1
        use_f2 = dp_solve(i + 1, f1, word[i]) + cost_f2
        dp[(i, f1, f2)] = min(use_f1, use_f2)
        return dp[(i, f1, f2)]

    return dp_solve(0, None, None)
function minimumDistance(word) {
    const getPos = (ch) => [Math.floor((ch.charCodeAt(0) - 'A'.charCodeAt(0)) / 6), (ch.charCodeAt(0) - 'A'.charCodeAt(0)) % 6];
    const dist = (pos1, pos2) => Math.abs(pos1[0] - pos2[0]) + Math.abs(pos1[1] - pos2[1]);
    const dp = new Map();

    const dp_solve = (i, f1, f2) => {
        if (i === word.length) return 0;
        const key = `${i}-${f1}-${f2}`;
        if (dp.has(key)) return dp.get(key);
        const posCurr = getPos(word[i]);
        const posF1 = f1 ? getPos(f1) : null;
        const posF2 = f2 ? getPos(f2) : null;
        const costF1 = posF1 ? dist(posF1, posCurr) : 0;
        const costF2 = posF2 ? dist(posF2, posCurr) : 0;
        const useF1 = dp_solve(i + 1, word[i], f2) + costF1;
        const useF2 = dp_solve(i + 1, f1, word[i]) + costF2;
        const result = Math.min(useF1, useF2);
        dp.set(key, result);
        return result;
    };

    return dp_solve(0, null, null);
}

This code uses a recursive function `dp_solve` which takes the current index `i` and the positions of the two fingers `f1`, `f2` and returns the minimum cost to type the word from that point onwards. The base case is when `i` equals the length of the word, returning 0 as there's nothing left to type.

The function `dist` calculates the Manhattan distance between two positions. The memoization technique uses a dictionary `dp` to store already computed results for specific states (i, f1, f2), thus reducing redundant computations.

Complexity

Time Complexity: O(n*26*26), where n is the length of the word and 26 represents possible states for each finger (since there are 26 letters).

Space Complexity: O(n*26*26) for storing results in the dp dictionary.

Try this approach in the editor

Approach 2: Dynamic Programming with Two-dimensional Array

This approach is a variation of the dynamic programming solution, using a two-dimensional array to maintain a tabulation of results instead of recursion with memoization. We precompute distances and use a bottom-up DP approach to fill our dp table.

At each step, we decide the best possible move for each finger to type the character at the current index with minimum cost.

class Solution {
    public int minimumDistance(String word) {
        int n = word.length();
        int[][] dp = new int[n][26];
        for (int[] row : dp)
            Arrays.fill(row, Integer.MAX_VALUE);
        dp[0][word.charAt(0) - 'A'] = 0;

        for (int i = 1; i < n; ++i) {
            int curr = word.charAt(i) - 'A';
            for (int j = 0; j < 26; ++j) {
                dp[i][curr] = Math.min(dp[i][curr], dp[i - 1][j] + dist(j, curr));
                dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + dist(word.charAt(i - 1) - 'A', curr));
            }
        }

        return Arrays.stream(dp[n - 1]).min().getAsInt();
    }

    private int dist(int a, int b) {
        if (a == -1) return 0;
        return Math.abs(a / 6 - b / 6) + Math.abs(a % 6 - b % 6);
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.minimumDistance("CAKE")); // Output: 3
    }
}
#include <iostream>
#include <vector>
#include <cmath>
#include <climits>
using namespace std;

int minimumDistance(string word) {
    auto dist = [](int a, int b) {
        if (a == -1) return 0;
        return abs(a / 6 - b / 6) + abs(a % 6 - b % 6);
    };

    int n = word.length();
    vector<vector<int>> dp(n, vector<int>(26, INT_MAX));
    dp[0][word[0] - 'A'] = 0;

    for (int i = 1; i < n; ++i) {
        int curr = word[i] - 'A';
        for (int j = 0; j < 26; ++j) {
            dp[i][curr] = min(dp[i][curr], dp[i-1][j] + dist(j, curr));
            dp[i][j] = min(dp[i][j], dp[i-1][j] + dist(word[i-1] - 'A', curr));
        }
    }
    return *min_element(dp[n - 1].begin(), dp[n - 1].end());
}

int main() {
    cout << minimumDistance("CAKE") << endl; // Output: 3
    return 0;
}

This Java solution follows a similar approach to the C++ solution but is implemented using Java syntax. We utilize a 2D array where dp[i][j] represents the minimum cost of typing up to the ith character with the jth finger at the ith step.

Complexity

Time Complexity: O(n * 26^2) where n is the length of the word.

Space Complexity: O(n * 26) for storing DP states.

Try this approach in the editor

Approach 3: Dynamic Programming

We define f[i][j][k] to represent the minimum distance after typing word[i], with finger 1 at position j and finger 2 at position k. Here, positions j and k represent the numbers corresponding to the letters, ranging from [0,..25]. Initially, f[i][j][k] = infty.

We implement a function dist(a, b) to represent the distance between positions a and b, i.e., dist(a, b) = |\frac{a}{6} - \frac{b}{6}| + |a bmod 6 - b bmod 6|.

Next, we consider typing word[0], i.e., the case with only one letter. There are two choices:

  • Finger 1 is at the position of word[0], and finger 2 is at any position. In this case, f[0][word[0]][k] = 0, where k \in [0,..25].
  • Finger 2 is at the position of word[0], and finger 1 is at any position. In this case, f[0][k][word[0]] = 0, where k \in [0,..25].

Then we consider typing word[1,..n-1]. Let the positions of the previous letter and the current letter be a and b, respectively. Next, we discuss the following cases:

If the current finger 1 is at position b, we enumerate the position j of finger 2. If the previous position a was also the position of finger 1, then f[i][b][j] = min(f[i][b][j], f[i-1][a][j] + dist(a, b)). If the position of finger 2 is the same as the previous position a, i.e., j = a, then we enumerate the position k of finger 1 in the previous position. In this case, f[i][b][j] = min(f[i][b][j], f[i-1][k][a] + dist(k, b)).

Similarly, if the current finger 2 is at position b, we enumerate the position j of finger 1. If the previous position a was also the position of finger 2, then f[i][j][b] = min(f[i][j][b], f[i-1][j][a] + dist(a, b)). If the position of finger 1 is the same as the previous position a, i.e., j = a, then we enumerate the position k of finger 2 in the previous position. In this case, f[i][j][b] = min(f[i][j][b], f[i-1][a][k] + dist(k, b)).

Finally, we enumerate the positions of finger 1 and finger 2 at the last position and take the minimum value as the answer.

The time complexity is O(n times |\Sigma|^2), and the space complexity is O(n times |\Sigma|^2). Here, n is the length of the string word, and |\Sigma| is the size of the alphabet, which is 26 in this problem.

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
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Dynamic Programming with State Representation

Time Complexity: O(n*26*26), where n is the length of the word and 26 represents possible states for each finger (since there are 26 letters).

Space Complexity: O(n*26*26) for storing results in the dp dictionary.

Dynamic Programming with Two-dimensional Array

Time Complexity: O(n * 26^2) where n is the length of the word.

Space Complexity: O(n * 26) for storing DP states.

Dynamic Programming–

Complexity analysis

ApproachTimeSpaceWhen to Use
Dynamic Programming with State RepresentationO(n * 26 * 26)O(26 * 26)Good for understanding the full DP state of both finger positions
Optimized DP with Two-dimensional ArrayO(n * 26)O(26)Preferred solution for interviews and large inputs

Frequently asked questions

Is Minimum Distance to Type a Word Using Two Fingers easy or hard?

Minimum Distance to Type a Word Using Two Fingers is categorized as a Hard problem on LeetCode. The difficulty comes from modeling the two-finger typing process and recognizing how to reduce the dynamic programming state from 26×26 possibilities to a more efficient representation.

Minimum Distance to Type a Word Using Two Fingers Python/Java solution

Python and Java implementations typically use dynamic programming with an array of size 26 to represent the free finger position. Each step updates the cost based on Manhattan distance between characters on the keyboard grid. The same logic translates easily to C++ and JavaScript.

How to solve Minimum Distance to Type a Word Using Two Fingers in O(n)?

Use dynamic programming with a one‑finger state. Maintain a DP array where each entry represents the position of the free finger while the other finger typed the previous character. For every new character, update costs for moving either finger and compute the Manhattan distance between keyboard coordinates.

What is the best approach for Minimum Distance to Type a Word Using Two Fingers?

The best approach uses dynamic programming with a reduced state where one finger position is tracked explicitly and the other implicitly represents the last typed character. This reduces the state space to 26 possibilities and leads to an O(n * 26) time solution. It efficiently calculates the minimum Manhattan distance required to type the entire word.

Is Minimum Distance to Type a Word Using Two Fingers asked at Google/Amazon/Meta?

Dynamic programming problems with state optimization like this frequently appear in interviews at companies such as Google, Amazon, and Meta. The problem tests DP modeling, state reduction, and grid distance calculations, which are common interview themes.

What data structure is used in Minimum Distance to Type a Word Using Two Fingers?

The core data structure is a dynamic programming array or table. It stores minimum movement costs for different finger position states while iterating through the input string. The keyboard layout is typically represented implicitly using coordinate calculations from character indices.

What is the time complexity of Minimum Distance to Type a Word Using Two Fingers?

The optimized dynamic programming solution runs in O(n * 26) time, where n is the length of the word. A more direct DP that tracks both finger positions has O(n * 26 * 26) time complexity. Space complexity ranges from O(26) to O(26 * 26) depending on the implementation.

Comments

Now write it yourselfClose this page and solve Minimum Distance to Type a Word Using Two Fingers in the editor, without looking.
Practise Minimum Distance to Type a Word Using Two Fingers