Skip to content

Commit 3e33c4d

Browse files
chore: add LeetCode daily solution
1 parent 47f4009 commit 3e33c4d

5 files changed

Lines changed: 125 additions & 0 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Minimum Distance to Type a Word Using Two Fingers (Hard)
2+
3+
**Problem ID:** 1320
4+
**Date:** 2026-04-12
5+
**Link:** https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/
6+
7+
## Approach
8+
9+
To solve the problem of finding the minimum distance to type a word using two fingers on a keyboard represented in a 2D plane, we can adopt a dynamic programming approach. Here’s a concise breakdown of the solution:
10+
11+
### Main Idea:
12+
The goal is to minimize the total distance traveled by two fingers as they type out the given word, where the distance between two letters is defined by their Manhattan distance on the keyboard layout. We will use dynamic programming to keep track of the minimum distances for typing each letter in the word while considering the positions of both fingers.
13+
14+
### Data Structures:
15+
1. **Distance Matrix**: Precompute the distances between all pairs of letters based on their coordinates on the keyboard. This will allow us to quickly look up the distance between any two letters.
16+
2. **Dynamic Programming Table**: Use a 3D DP table `dp[i][j][k]`, where:
17+
- `i` represents the index of the current letter in the word.
18+
- `j` represents the position of the first finger (the last letter typed by finger 1).
19+
- `k` represents the position of the second finger (the last letter typed by finger 2).
20+
The value `dp[i][j][k]` will store the minimum distance required to type the first `i` letters of the word with finger 1 on letter `j` and finger 2 on letter `k`.
21+
22+
### Approach:
23+
1. **Initialization**: Start by initializing the DP table for the first letter of the word, allowing both fingers to start on any letter without any initial cost.
24+
2. **Transition**: For each letter in the word (from the second letter onward):
25+
- Iterate through all possible positions of the two fingers (from the previous letter).
26+
- Calculate the cost of moving either finger to the current letter and update the DP table accordingly.
27+
- The transition will consider moving either finger to the current letter and accumulating the distance based on the previous positions of both fingers.
28+
3. **Final Computation**: After processing all letters, the answer will be the minimum value in the last layer of the DP table, which corresponds to typing the entire word.
29+
30+
### Complexity:
31+
- **Time Complexity**: O(n * 26 * 26), where `n` is the length of the word (up to 300) and 26 represents the number of uppercase English letters. This is because for each letter, we consider all pairs of finger positions.
32+
- **Space Complexity**: O(n * 26 * 26) for the DP table, although optimizations can be made to reduce space usage by only storing the last two layers of the DP table.
33+
34+
This approach ensures that we systematically explore all possible configurations of finger placements while efficiently calculating the minimum distance required to type the word.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
private final int[][] keyboard = new int[26][2];
3+
4+
public int minimumDistance(String word) {
5+
initializeKeyboard();
6+
int n = word.length();
7+
Integer[][][] dp = new Integer[n + 1][27][27];
8+
return dfs(word, 0, 26, 26, dp);
9+
}
10+
11+
private int dfs(String word, int index, int finger1, int finger2, Integer[][][] dp) {
12+
if (index == word.length()) return 0;
13+
if (dp[index][finger1][finger2] != null) return dp[index][finger1][finger2];
14+
15+
int letterIndex = word.charAt(index) - 'A';
16+
int distance1 = (finger1 == 26) ? 0 : getDistance(finger1, letterIndex);
17+
int distance2 = (finger2 == 26) ? 0 : getDistance(finger2, letterIndex);
18+
19+
int moveFinger1 = distance1 + dfs(word, index + 1, letterIndex, finger2, dp);
20+
int moveFinger2 = distance2 + dfs(word, index + 1, finger1, letterIndex, dp);
21+
22+
dp[index][finger1][finger2] = Math.min(moveFinger1, moveFinger2);
23+
return dp[index][finger1][finger2];
24+
}
25+
26+
private int getDistance(int finger, int letter) {
27+
return Math.abs(keyboard[finger][0] - keyboard[letter][0]) + Math.abs(keyboard[finger][1] - keyboard[letter][1]);
28+
}
29+
30+
private void initializeKeyboard() {
31+
for (int i = 0; i < 26; i++) {
32+
keyboard[i][0] = i / 6; // x-coordinate
33+
keyboard[i][1] = i % 6; // y-coordinate
34+
}
35+
}
36+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
var minimumDistance = function(word) {
2+
const positions = {};
3+
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
4+
5+
for (let i = 0; i < alphabet.length; i++) {
6+
positions[alphabet[i]] = [Math.floor(i / 6), i % 6];
7+
}
8+
9+
const n = word.length;
10+
const dp = Array.from({ length: n + 1 }, () => Array(27).fill(Infinity));
11+
dp[0][26] = 0; // Starting with both fingers free
12+
13+
for (let i = 0; i < n; i++) {
14+
const [x1, y1] = positions[word[i]];
15+
for (let j = 0; j <= 26; j++) {
16+
if (dp[i][j] === Infinity) continue;
17+
// Move finger 1 to current letter
18+
const dist1 = j === 26 ? 0 : Math.abs(x1 - positions[alphabet[j]][0]) + Math.abs(y1 - positions[alphabet[j]][1]);
19+
dp[i + 1][i] = Math.min(dp[i + 1][i], dp[i][j] + dist1);
20+
// Move finger 2 to current letter
21+
const dist2 = j === 26 ? 0 : Math.abs(x1 - positions[alphabet[j]][0]) + Math.abs(y1 - positions[alphabet[j]][1]);
22+
dp[i + 1][j] = Math.min(dp[i + 1][j], dp[i][j] + dist2);
23+
}
24+
}
25+
26+
return Math.min(...dp[n]);
27+
};
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution:
2+
def minimumDistance(self, word: str) -> int:
3+
# Keyboard layout coordinates
4+
keyboard = {chr(i): (i // 6, i % 6) for i in range(ord('A'), ord('Z') + 1)}
5+
6+
n = len(word)
7+
dp = [[[float('inf')] * 26 for _ in range(26)] for _ in range(n + 1)]
8+
9+
# Initial positions of fingers are free
10+
for i in range(26):
11+
dp[0][i][i] = 0
12+
13+
for i in range(1, n + 1):
14+
curr_char = word[i - 1]
15+
curr_x, curr_y = keyboard[curr_char]
16+
for j in range(26):
17+
for k in range(26):
18+
# Move finger 1 to current character
19+
dp[i][ord(curr_char) - ord('A')][k] = min(dp[i][ord(curr_char) - ord('A')][k],
20+
dp[i - 1][j][k] + (abs(curr_x - keyboard[chr(j + ord('A'))][0]) +
21+
abs(curr_y - keyboard[chr(j + ord('A'))][1])))
22+
# Move finger 2 to current character
23+
dp[i][j][ord(curr_char) - ord('A')] = min(dp[i][j][ord(curr_char) - ord('A')],
24+
dp[i - 1][j][k] + (abs(curr_x - keyboard[chr(k + ord('A'))][0]) +
25+
abs(curr_y - keyboard[chr(k + ord('A'))][1])))
26+
27+
return min(dp[n][j][k] for j in range(26) for k in range(26))

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -421,3 +421,4 @@ Through completing the Blind 75 and NeetCode 150, you will have mastered:
421421
- 2026-04-09 — [XOR After Range Multiplication Queries II](https://leetcode.com/problems/xor-after-range-multiplication-queries-ii/) (Hard) → `Hard/2026-04-09-3655-XOR-After-Range-Multiplication-Queries-II`
422422
- 2026-04-10 — [Minimum Distance Between Three Equal Elements I](https://leetcode.com/problems/minimum-distance-between-three-equal-elements-i/) (Easy) → `Easy/2026-04-10-3740-Minimum-Distance-Between-Three-Equal-Elements-I`
423423
- 2026-04-11 — [Minimum Distance Between Three Equal Elements II](https://leetcode.com/problems/minimum-distance-between-three-equal-elements-ii/) (Medium) → `Medium/2026-04-11-3741-Minimum-Distance-Between-Three-Equal-Elements-II`
424+
- 2026-04-12 — [Minimum Distance to Type a Word Using Two Fingers](https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/) (Hard) → `Hard/2026-04-12-1320-Minimum-Distance-to-Type-a-Word-Using-Two-Fingers`

0 commit comments

Comments
 (0)