Python 0500.py
class Solution:
def findWords(self, words: List[str]) -> List[str]:
rows = {
"q": 1, "w": 1, "e": 1, "r": 1, "t": 1, "y": 1, "u": 1, "i": 1, "o": 1, "p": 1,
"a": 2, "s": 2, "d": 2, "f": 2, "g": 2, "h": 2, "j": 2, "k": 2, "l": 2,
"z": 4, "x": 4, "c": 4, "v": 4, "b": 4, "n": 4, "m": 4 }
result = []
for w in words:
mask = 0
for c in w.lower():
mask |= rows[c]
if mask in [ 1, 2, 4 ]:
result.append(w)
return result
Difficulty
and has an acceptance rate of about 74% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The findWords method receives a list of strings and returns a new list containing only those words that can be typed using letters from a single row of a standard QWERTY keyboard. The implementation normalizes each word to lowercase, maps each character to its keyboard row, aggregates the rows with a bitwise mask, and finally selects words whose mask corresponds to exactly one row.
Key Steps
Mapping characters to rows
A dictionary named rows assigns an integer identifier to every alphabetic character based on its keyboard row. The identifiers are chosen as powers of two (1, 2, 4) so that they can be combined with a bitwise OR operation.
rows = {
"q": 1, "w": 1, "e": 1, "r": 1, "t": 1, "y": 1, "u": 1, "i": 1, "o": 1, "p": 1,
"a": 2, "s": 2, "d": 2, "f": 2, "g": 2, "h": 2, "j": 2, "k": 2, "l": 2,
"z": 4, "x": 4, "c": 4, "v": 4, "b": 4, "n": 4, "m": 4
}
Iterating over the input words
An empty list result is prepared to collect qualifying words. The outer loop walks through each word in the supplied words list.
result = []
for w in words:
...
Building the row mask for a word
For each word, a variable mask starts at zero. The inner loop processes every character after converting it to lowercase. The character’s row identifier is retrieved from rows and merged into mask using the bitwise OR operator. This accumulates all distinct rows used by the word.
mask = 0
for c in w.lower():
mask |= rows[c]
Selecting words that belong to a single row
After the mask is constructed, a simple membership test checks whether the mask equals one of the three single-row identifiers (1, 2, 4). If the condition holds, the original word (preserving its original case) is appended to result.
if mask in [1, 2, 4]:
result.append(w)
Returning the filtered list
When all words have been examined, the method returns the populated result list.
return result
Edge Cases Handled
The algorithm treats uppercase input transparently because each character is explicitly lowered before lookup, ensuring that words with mixed case are evaluated correctly. An empty string yields a mask of zero; since zero is not among the accepted single-row values, the empty word is automatically excluded. The use of a dictionary for row lookup guarantees constant-time access for any alphabetic character, and the design implicitly assumes that all characters in the input belong to the English alphabet; any non-alphabetic character would raise a lookup failure, which aligns with the expectation that the problem domain consists solely of alphabetic words.
Performance Optimizations
The choice of power-of-two identifiers enables the aggregation of row information with a single integer using bitwise OR, avoiding the overhead of constructing auxiliary collections such as sets or lists for each word. Dictionary lookups provide O(1) access to row identifiers, and the mask comparison against a short literal list is a fast operation. By operating directly on integer masks, the implementation reduces memory churn and improves cache locality, leading to efficient processing even for large input arrays.
ELI5 - Simplified Explanation
Imagine there is a magical keyboard with three rows of letters. The top row has letters like q and p, the middle row has letters like a and l, and the bottom row has letters like z and m. This code works like a tiny referee checking words to see if they follow a special rule.
The rule is that all the letters in a word must live on the exact same row on the keyboard. First, the code looks at every letter in a word and finds out which row it belongs to. It keeps track of these row numbers by adding them together. If a word only uses letters from the first row, its total score stays as one. If it only uses letters from the second row, the score stays as two, and for the third row, it stays as four.
After checking all the letters in a single word, the code looks at the final score. If the score is one, two, or four, it means every single letter came from only one row. When that happens, the word is collected into a special list to keep safe. The code repeats this process for every word provided until all the words have been checked.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | Go | C# | TS | |||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| Krazune | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| Krazune | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 455: Assign Cookies
- problem 575: Distribute Candies
- problem 1009: Complement of Base 10 Integer
- problem 1071: Greatest Common Divisor of Strings
- problem 1299: Replace Elements with Greatest Element on Right Side
- problem 1748: Sum of Unique Elements
- problem 1979: Find Greatest Common Divisor of Array
- problem 2148: Count Elements With Strictly Smaller and Greater Elements
- problem 2309: Greatest English Letter in Upper and Lower Case
- problem 216: Combination Sum III
- problem 229: Majority Element II
- problem 373: Find K Pairs with Smallest Sums
- problem 470: Implement Rand10() Using Rand7()
- problem 503: Next Greater Element II
- problem 556: Next Greater Element III
- problem 622: Design Circular Queue
- problem 1262: Greatest Sum Divisible by Three
- problem 2657: Find the Prefix Common Array of Two Arrays
- problem 2807: Insert Greatest Common Divisors in Linked List
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality