array and hashmap December 1, 2022

Single row keyboard

Time O(n) Space O(1) Open original problem

We will iterate over the word, find the index of the character in the keyboard and add the difference between the current and previous index to the result.

class Solution:
    def calculateTime(self, keyboard: str, word: str) -> int:
        index = {ch: i for i, ch in enumerate(keyboard)}
        res = 0
        prev = 0
        for ch in word:
            res += abs(index[ch] - prev)
            prev = index[ch]
        return res

Time complexity: O(n)
Space complexity: O(1)