Single-Row Keyboard — LeetCode 1165 Python Solution
EasyLeetCode PremiumHash TableString
- Problem
- #1165
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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
LeetCode 1169Invalid TransactionsMediumLeetCode 1160Find Words That Can Be Formed by CharactersEasyLeetCode 1170Compare Strings by Frequency of the Smallest CharacterMediumLeetCode 1156Swap For Longest Repeated Character SubstringMediumLeetCode 3Longest Substring Without Repeating CharactersMediumLeetCode 12Integer to RomanMedium
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.