Problem Description
You have a keyboard layout where each English uppercase letter is located at some coordinate. Given the string word
, return the minimum total distance to type such string using only two fingers. The distance between two coordinates is defined as the Manhattan distance.
Key Insights
- Each letter corresponds to a unique coordinate on the keyboard.
- The problem can be approached using dynamic programming to minimize the distance traveled by two fingers as they type each letter.
- The initial positions of the fingers are free and do not contribute to the total distance.
- The strategy involves calculating the distance for both fingers to each letter and deciding the optimal finger to use.
Space and Time Complexity
Time Complexity: O(n^2), where n is the length of the word, as we are considering all pairs of positions for the two fingers. Space Complexity: O(n), for storing the distances and the dynamic programming table.
Solution
To solve this problem, we will use a dynamic programming approach. We can maintain a DP table where dp[i][j]
represents the minimum distance to type the first k
letters of the word using the first finger at position i
and the second finger at position j
. We will iterate through the word and calculate the distance for every possible finger position, updating our DP table accordingly.
The key steps are:
- Identify the coordinates of each letter on the keyboard.
- Initialize the first entries of the DP table considering the free initial positions of the fingers.
- For each subsequent letter in the word, calculate the distance from the last typed letters to the current letter for both fingers.
- Update the DP table with the minimum distance found.