Single-Row Keyboard — LeetCode 1165 Python Solution

EasyLeetCode PremiumHash TableString
Problem
#1165
Pattern
Hash Map
Reading time
2 min

The problem

There is a special keyboard with all keys in a single row. Given a string keyboard of length 26 indicating the layout of the keyboard (indexed from 0 to 25).

Example

Input
keyboard = "abcdefghijklmnopqrstuvwxyz", word = "cba"
Output
4
Explanation
The index moves from 0 to 2 to write 'c' then to 1 to write 'b' then to 0 again to write 'a'.

Python solution

Python
class Solution:
    def calculateTime(self, keyboard: str, word: str) -> int:
        pos = {c: i for i, c in enumerate(keyboard)}
        ans = i = 0
        for c in word:
            ans += abs(pos[c] - i)
            i = pos[c]
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(C) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1165. Single-Row Keyboard is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1165. Single-Row Keyboard?
LeetCode 1165. Single-Row Keyboard is rated Easy on LeetCode.
What is the time complexity of LeetCode 1165. Single-Row Keyboard?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1165. Single-Row Keyboard?
The Python solution on this page uses O(C) auxiliary space.
What topics does LeetCode 1165. Single-Row Keyboard cover?
LeetCode 1165. Single-Row Keyboard is tagged Hash Table and String on LeetCode.
Is LeetCode 1165. Single-Row Keyboard a premium problem?
Yes. LeetCode 1165. Single-Row Keyboard is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview