[
string
hash table
]
Leetcode 1165 Single-Row Keyboard
Problem statement
https://leetcode.com/problems/single-row-keyboard/
Solution
First, collect all places for all letters in keyboard. Then iterate through word and add absolute difference to answer. Also we need to deal with first letter, for this I add keyboard[0] to the start of word.
Complexity
Time complexity is O(26 + n), space complexity is O(26).
Code
class Solution:
def calculateTime(self, keyboard, word):
places = {s: i for i, s in enumerate(keyboard)}
ans = 0
for x, y in zip(word, keyboard[0] + word):
ans += abs(places[x] - places[y])
return ans