#1320

Minimum Distance to Type a Word Using Two Fingers

Hard
StringDynamic Programming
LeetCode ↗

Approaches

💡

Intuition

Time Space

The brute force approach considers all possible placements of the two fingers for each character in the word. It calculates the distance for each possible combination, which can be quite inefficient.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a variable to store the minimum distance.
  2. 2Step 2: For each character in the word, iterate through all possible positions of the two fingers.
  3. 3Step 3: Calculate the distance for each finger movement and update the minimum distance accordingly.
solution.py26 lines
1# Full working Python code
2from itertools import product
3
4def minDistance(word):
5    # Keyboard layout coordinates
6    coords = {'A': (0, 0), 'B': (0, 1), 'C': (0, 2), 'D': (0, 3), 'E': (0, 4),
7              'F': (1, 0), 'G': (1, 1), 'H': (1, 2), 'I': (1, 3), 'J': (1, 4),
8              'K': (2, 0), 'L': (2, 1), 'M': (2, 2), 'N': (2, 3), 'O': (2, 4),
9              'P': (3, 0), 'Q': (3, 1), 'R': (3, 2), 'S': (3, 3), 'T': (3, 4),
10              'U': (4, 0), 'V': (4, 1), 'W': (4, 2), 'X': (4, 3), 'Y': (4, 4), 'Z': (4, 5)}
11    n = len(word)
12    min_dist = float('inf')
13
14    for i in range(n):
15        for j in range(i + 1, n):
16            finger1_pos = coords[word[i]]
17            finger2_pos = coords[word[j]]
18            total_distance = 0
19            for k in range(n):
20                if k == i:
21                    total_distance += abs(finger1_pos[0] - coords[word[k]][0]) + abs(finger1_pos[1] - coords[word[k]][1])
22                elif k == j:
23                    total_distance += abs(finger2_pos[0] - coords[word[k]][0]) + abs(finger2_pos[1] - coords[word[k]][1])
24            min_dist = min(min_dist, total_distance)
25    return min_dist
26minDistance('CAKE')

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.