#500
Keyboard Row
EasyArrayHash TableStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a set to map each character to its respective row, allowing for quick lookups. This reduces the need for multiple checks and improves efficiency.
⚙️
Algorithm
3 steps- 1Step 1: Create a mapping of each character to its corresponding keyboard row.
- 2Step 2: For each word, convert it to lowercase and check the row of the first character.
- 3Step 3: Verify if all characters belong to the same row using the mapping.
solution.py11 lines
1def findWords(words):
2 row_map = {c: 1 for c in 'qwertyuiop'}
3 row_map.update({c: 2 for c in 'asdfghjkl'})
4 row_map.update({c: 3 for c in 'zxcvbnm'})
5 result = []
6 for word in words:
7 lower_word = word.lower()
8 row = row_map[lower_word[0]]
9 if all(row_map[c] == row for c in lower_word):
10 result.append(word)
11 return resultℹ
Complexity note: The time complexity is O(n) since we only traverse each word once and perform constant-time lookups for each character. The space complexity is O(n) for the row mapping.
- 1Understanding character mapping is crucial for efficient lookups.
- 2Case insensitivity can be handled by converting to lowercase.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.