EasyNo. 1165LeetCode Premium
Single-Row Keyboard — LeetCode 1165 Python Solution
- Pattern
- Hash Map
- Topics
- Hash Table, String
- 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
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
- Time
- O(n)
- Space · auxiliary
- O(C)
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
| No. | Problem | Difficulty |
|---|---|---|
| 1169 | Invalid Transactions | Medium |
| 1160 | Find Words That Can Be Formed by Characters | Easy |
| 1170 | Compare Strings by Frequency of the Smallest Character | Medium |
| 1156 | Swap For Longest Repeated Character Substring | Medium |
| 0003 | Longest Substring Without Repeating Characters | Medium |
| 0012 | Integer to Roman | Medium |
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.