Minimum Distance to Type a Word Using Two Fingers LeetCode solution in Python
1from functools import cache234class Solution:5def minimumDistance(self, word: str) -> int:6alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"7COL = 68index = {c: (i // COL, i % COL) for i, c in enumerate(alphabets)}910def dist(a, b):11return abs(index[a][0] - index[b][0]) + abs(index[a][1] - index[b][1])1213@cache14def dfs(lhand, rhand, i):15if i == len(word):16return 017res = float("inf")18res = (19min(res, dfs(word[i], rhand, i + 1))20if lhand == -121else min(res, dist(lhand, word[i]) + dfs(word[i], rhand, i + 1))22)23res = (24min(res, dfs(lhand, word[i], i + 1))25if rhand == -126else min(res, dist(word[i], rhand) + dfs(lhand, word[i], i + 1))27)28return res2930return dfs(-1, -1, 0)