1320. Minimum Distance to Type a Word Using Two Fingers
Description
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.
Solutions
Solution: Dynamic Programming
- Time complexity: O(272n -> n)
- Space complexity: O(272n -> n)
JavaScript
js
/**
* @param {string} word
* @return {number}
*/
const minimumDistance = function (word) {
const BASE_CODE = 'A'.charCodeAt(0);
const COLS = 6;
const n = word.length;
const memo = new Map();
const getCoordinate = letter => {
const code = letter.charCodeAt(0) - BASE_CODE;
const x = code % COLS;
const y = Math.floor(code / 6);
return { x, y };
};
const getDistance = (finger, target) => {
if (!finger) return 0;
const { x: fingerX, y: fingerY } = getCoordinate(finger);
const { x: targetX, y: targetY } = getCoordinate(target);
return Math.abs(fingerX - targetX) + Math.abs(fingerY - targetY);
};
const typeWord = (index, finger1, finger2) => {
if (index >= n) return 0;
const key = `${index},${finger1},${finger2}`;
if (memo.has(key)) return memo.get(key);
const letter = word[index];
const distance1 = getDistance(finger1, letter);
const distance2 = getDistance(finger2, letter);
const total1 = distance1 + typeWord(index + 1, letter, finger2);
const total2 = distance2 + typeWord(index + 1, finger1, letter);
const result = Math.min(total1, total2);
memo.set(key, result);
return result;
};
return typeWord(0, null, null);
};