Problem Description
Given an uppercase string word, determine the minimum total Manhattan distance required to type the word using two fingers on a special keyboard. The keyboard is laid out in the X-Y plane so that letter 'A' is at (0, 0), 'B' is at (0, 1), etc., and each movement cost is the Manhattan distance between two key coordinates. The initial positions of both fingers are free (no cost). For each letter to type (in order), you can choose which finger to move. The task is to plan finger movements such that the total moving distance is minimized.
Key Insights
- Use dynamic programming to decide which finger to move at each letter.
- Represent the state by the last letters that each finger pressed (or a special initial state).
- The next letter to type is determined by the maximum of the two finger positions plus one.
- The cost for moving a finger is the Manhattan distance between keys.
- Leverage memoization to avoid repeated calculations in overlapping subproblems.
Space and Time Complexity
Time Complexity: O(n^2), where n is the length of the word, because each state is determined by two finger positions. Space Complexity: O(n^2) for the memoization table storing intermediate results.
Solution
We solve the problem using a recursive dynamic programming approach with memoization. Define a function f(i, j) where:
- i: the index of the letter last typed by finger1 (or -1 if it hasn't been used yet)
- j: the index of the letter last typed by finger2 (or -1 if it hasn't been used yet)
The next letter to type has index k = max(i, j) + 1. At each step, we choose to move either finger1 or finger2 to type the next letter; if a finger has never been used (i.e. index -1), moving it incurs no cost. Otherwise, moving a finger costs the Manhattan distance between its current key and the next key.
The Manhattan distance between two letters is computed by converting the letter's position to (row, col) using:
row = (letter index) // 6
col = (letter index) % 6
We use recursion with memoization to explore both choices at each step and return the minimal cost.