A standard US keyboard has three rows of letter keys: qwertyuiop on top, asdfghjkl in the middle and zxcvbnm at the bottom.
You are given a list of strings words. Return the words you could type while using keys from a single row only. Upper-case and lower-case forms of a letter sit on the same key, so case does not matter. Keep the words in the order they appear in the input.
Example 1
Input: words = ["Type", "Zinc", "Lad", "Cave"] Output: ["Type", "Lad"] Why: Type uses the top row, Lad the middle one
2 more examples and the constraints
Example 2
Input: words = ["moon"] Output: [] Why: m is on the bottom row, o on the top
Example 3
Input: words = ["ZxCv", "pIPe", "Ash"] Output: ["ZxCv", "pIPe", "Ash"] Why: each word stays on one row, whatever the case
Constraints
- 1 ≤ length of words ≤ 20
- 1 ≤ length of each word ≤ 100
- Words contain only English letters, upper-case or lower-case
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Test every rowO(L·26)
- Letter-to-row tableO(L)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 20 words of 100 letters | Verdict |
|---|---|---|---|
| Test every row | O(L·26) | Passes; repeats row searches | |
| Letter-to-row table | O(L) | Best; one lookup per letter |
L = total number of letters in all words.
Edge cases to test
- Mixed case. "pIPe" must be lower-cased for the lookup, but returned as "pIPe".
- One-letter words. A single letter is always on one row, so it is always kept.
- No word fits. Return an empty list, not null.
- Repeated letters. "sass" only touches the middle row; repeats change nothing.
Common mistakes
- Forgetting to lower-case, so "T" is not found in any row.
- Returning the lower-cased word instead of the original.
- Checking only that each letter is in some row, which every letter always is.
How to talk through it
- 1Clarify. Is case ignored? Must the output keep the input order and the original spelling?
- 2Give the simple check. Test each word against each of the three row strings.
- 3Precompute. A 26-entry table from letter to row turns each check into one lookup.
- 4Code it. Take the first letter's row and stop at the first letter that disagrees.
- 5Test out loud. Run a mixed-case word, a one-letter word and a word that fails late.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?