Problem 500

Abstract / Summary

Find all words that can be typed using letters from a single row of the keyboard.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
16 lines | 584 bytes | submitted August 14, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 74% (400k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.92 | σ = 1.59

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
37 links | 23 authors | 10 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

20 solutions   August 14, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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