[Python] Easy Solution | very fast and efficient | O(n)
Intuition\n- Looping through the array, one hand is always at the previous letter. So we have to save the last element and the cost of all possible letter for t
# Intuition\n- Looping through the array, one hand is always at the previous letter. So we have to save the last element and the cost of all possible letter for the second hand.\n- If we choose to change the first hand to the current letter, every cost in will increase by the distance of the previous to current letter.\n- If we choose the second hand to change to the current letter, we have to add the cost and distance to the current letter for all possible letters. Now we just update the previous letter in the cost array.\n- Calculate the distance (function `get_distance`): get row and col of the letter, apply manhattan distance.\n\n# Complexity\nTime: `O(n)`\nSpace: `O(1)`\n\n# Code\n```python3 []\ndef get_distance(a, b):\n    r1, c1 = divmod(ord(a) - ord(\'A\'), 6)\n    r2, c2 = divmod(ord(b) - ord(\'A\'), 6)\n    return abs(r1 - r2) + abs(c1 - c2)\n\nclass Solution:\n    def minimumDistance(self, word: str) -> int:\n        previous = word[0]\n        cost = [0] * 26\n        for letter in word:\n            prev_cur = get_distance(letter, previous)\n            small = float(\'inf\')\n            for i, val in enumerate(cost):\n                cost[i] += prev_cur\n                dist = get_distance(letter, chr(i + ord(\'A\')))\n                small = min(small, val+dist)\n            \n            idx = ord(previous) - ord(\'A\')\n            cost[idx] = min(cost[idx], small)\n            previous = letter\n        return min(cost)\n```
['Python3']