Single row keyboard

December 1, 2022

array-and-hashmap

Problem URL: Single row keyboard

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)