Keyboard Row (LeetCode 500): Solution and Explanation

Easy
Array
Hash Table
String

Tag every letter with its keyboard row, then keep a word only when all of its letters carry the same tag as its first letter.

Intuition

Each letter lives on exactly one of three rows, so the question for a word is simply whether its letters ever switch rows.

The first letter decides which row the word has to stay on. From then on, a single letter from another row is enough to reject the word.

Case does not change the key, so lowercase each letter before looking up its row, but return the word as it was written.

Approach: Row lookup table

  1. Build a table from each of the 26 letters to its row index 0, 1 or 2.
  2. For each word, lowercase it and read the row of its first letter as the target.
  3. Scan the remaining letters and stop at the first one whose row differs from the target.
  4. If no letter differed, append the original word to the answer.

Step-by-step example

words = ["Hello","Alaska","Dad","Peace"]
  1. "hello": h is on the middle row, then e is on the top row. Rejected.
  2. "alaska": a, l, a, s, k, a are all on the middle row. Kept.
  3. "dad": d, a, d are all on the middle row. Kept.
  4. "peace": p is on the top row, then e matches, then a is on the middle row. Rejected.
  5. The answer is ["Alaska","Dad"].

Code: Python, Java, C++

1class Solution:
2    def findWords(self, words: List[str]) -> List[str]:
3        rows = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
4        row_of = {c: i for i, r in enumerate(rows) for c in r}
5        result = []
6        for word in words:
7            lower = word.lower()
8            target = row_of[lower[0]]
9            if all(row_of[c] == target for c in lower):
10                result.append(word)
11        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(L)

L is the total number of letters across all words. Each letter is looked up at most once.

Space

O(1)

The lookup table has 26 entries. The output list is not counted.

Other approaches

Set subset test (time O(L), space O(L))

Turn each row into a set and check whether the set of a word's lowercase letters is a subset of any row set. Short to write, but it builds a new set per word.

Regular expression (time O(L), space O(1))

Match each word against a case-insensitive pattern like ^([qwertyuiop]+|[asdfghjkl]+|[zxcvbnm]+)$. Compact, but harder to reason about and slower than a table.

Common mistakes

  • Forgetting uppercase letters. "Alaska" starts with a capital A, which must map to the same row as a.
  • Returning the lowercased word instead of the original. The expected output keeps the input's capitals.
  • Comparing each letter only with its neighbour is fine, but comparing with a fixed row chosen elsewhere (for example always row 0) is not; the first letter must pick the row.

Frequently asked questions

Why use the first letter as the target row?

Every letter must share one row, so whichever row the first letter sits on is the only row the word could possibly use. Any later mismatch proves the word needs two rows.

Does the order of the output matter?

Yes. Return the qualifying words in the same order they appear in the input.

Can I stop scanning a word early?

Yes. As soon as one letter is on a different row the word is out, so break and move to the next word.