JustPaste.it

Keyboard Row (LeetCode 500): Map Each Letter to Its Row Once

Keyboard Row (LeetCode 500): Map Each Letter to Its Row Once

Given a list of words, return the ones that can be typed using letters from only one row of an American QWERTY keyboard. ["Hello","Alaska","Dad","Peace"] returns ["Alaska","Dad"].

Build a letter-to-row map

Precompute which row each letter lives on, then check that every letter of a word shares the row of its first letter.

ROWS = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
ROW_OF = {c: i for i, r in enumerate(ROWS) for c in r}

def find_words(words):
    out = []
    for w in words:
        lw = w.lower()
        r = ROW_OF[lw[0]]
        if all(ROW_OF[c] == r for c in lw):
            out.append(w)
    return out

Each word is scanned once, so the total cost is O(total characters), and the map is a constant 26 entries.

A set-based alternative

set(lw) <= set(row) for any of the three rows is shorter and reads nicely, but it builds a set per word. Mention both and say which you'd ship.

Edge cases

  • Mixed case: lowercase before lookup, but return the original word.
  • Single-letter words always qualify.

Interview tip

Easy problems are judged on clarity. Say the plan in one sentence before coding. If you want to practise talking through warm-ups like this, Linkjob.ai can help you rehearse.

Disclosure: I work on Linkjob AI.