Keyboard Row
Given an array of strings words, return the words that can be typed using letters from only one row of a US keyboard. Keep them in their original order and capitalization.
The three letter rows are:
- First row:
qwertyuiop - Second row:
asdfghjkl - Third row:
zxcvbnm
Uppercase and lowercase letters count as the same key.
Example 1
Input: words = ["Hello", "Alaska", "Dad", "Peace"] Output: ["Alaska", "Dad"]
Every letter of Alaska and Dad is on the second row. Hello and Peace use more than one row.
Example 2
Input: words = ["omk"] Output: []
Constraints
1 <= words.length <= 201 <= words[i].length <= 100words[i]contains only uppercase and lowercase English letters.
Approach
Searching all three row strings for every letter works, but it repeats the same lookups. Instead, build a map from each letter to its row number once. Then a word can be typed on one row exactly when every letter maps to the same row as its first letter.
Compare lowercase letters, since A and a are the same key, but add the original word to the result so its capitalization is preserved.
Steps
- Build a map from each letter to its row: 0 for
qwertyuiop, 1 forasdfghjkland 2 forzxcvbnm. - For each word, lowercase it and look up the row of its first letter.
- If every letter maps to that row, add the original word to the result.
- Return the result.
from typing import List
def find_words(words: List[str]) -> List[str]:
rows = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
row_of = {ch: i for i, row in enumerate(rows) for ch in row} # letter -> row number
result = []
for word in words:
lower = word.lower()
first_row = row_of[lower[0]]
if all(row_of[ch] == first_row for ch in lower):
result.append(word) # keep the original capitalization
return resultComplexity
- Time:
O(L), whereLis the total number of letters across all words. - Space:
O(1)for the 26-letter map, not counting the output.
Common mistakes
- Forgetting uppercase letters.
Alaskastarts with a capitalA, which is on the same key asa. - Returning lowercased words. The output should keep each word exactly as it was given.
- Checking only that each letter is on some row. Every letter has to be on the same row as the first one.