LeetCode Problem Workspace

Keyboard Row

Identify all words from a list that can be typed using letters from only one row of a standard American keyboard.

category

3

Topics

code_blocks

6

Code langs

hub

3

Related

Practice Focus

Easy · Array scanning plus hash lookup

bolt

Answer-first summary

Identify all words from a list that can be typed using letters from only one row of a standard American keyboard.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Array scanning plus hash lookup

Try AiBox Copilotarrow_forward

To solve the Keyboard Row problem, quickly map each letter to its keyboard row and scan each word for consistency. Using hash sets for each row ensures fast membership checks, allowing efficient verification if all letters in a word belong to the same row. This approach leverages the Array scanning plus hash lookup pattern for optimal performance on small input lists.

Problem Statement

Given an array of strings words, return all words that can be typed using letters from only one row of an American keyboard. Letters are case-insensitive, and the same letter in uppercase or lowercase counts as the same row. You must determine efficiently whether each word's letters all exist in a single row.

For example, with words = ["Hello","Alaska","Dad","Peace"], the correct output is ["Alaska","Dad"]. Use array scanning combined with hash-based row lookup to check each word. Constraints: 1 <= words.length <= 20, 1 <= words[i].length <= 100, words[i] consists of English letters only.

Examples

Example 1

Input: words = ["Hello","Alaska","Dad","Peace"]

Output: ["Alaska","Dad"]

Both "a" and "A" are in the 2nd row of the American keyboard due to case insensitivity.

Example 2

Input: words = ["omk"]

Output: []

Example details omitted.

Example 3

Input: words = ["adsdf","sfd"]

Output: ["adsdf","sfd"]

Example details omitted.

Constraints

  • 1 <= words.length <= 20
  • 1 <= words[i].length <= 100
  • words[i] consists of English letters (both lowercase and uppercase).

Solution Approach

Map letters to keyboard rows

Create a hash map where each lowercase letter maps to its corresponding keyboard row index (0, 1, or 2). This enables O(1) lookup for any letter and ensures case insensitivity is handled by converting letters to lowercase.

Scan each word and validate row

Iterate through each word in the array and check if all letters belong to the same row using the hash map. If a mismatch is found, discard the word; otherwise, add it to the result list. This directly applies the Array scanning plus hash lookup pattern.

Collect results efficiently

Maintain a list to store valid words while scanning. Since each word is checked independently, the overall time complexity is linear with respect to the total number of letters across all words, and space complexity depends on storing row mappings and the output list.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

Time complexity is O(n * m), where n is the number of words and m is the average word length, because each letter is checked once. Space complexity is O(1) for the row map plus O(k) for the output list, where k is the number of valid words.

What Interviewers Usually Probe

  • Expect quick mapping of letters to rows with hash structures.
  • Look for handling both uppercase and lowercase consistently.
  • Check awareness of scanning each word efficiently without redundant operations.

Common Pitfalls or Variants

Common pitfalls

  • Failing to handle case-insensitivity by not converting letters to lowercase.
  • Incorrectly checking only the first letter instead of verifying all letters in a word.
  • Using nested loops unnecessarily, increasing time complexity beyond linear scanning.

Follow-up variants

  • Return the indices of words instead of the words themselves if they can be typed on one row.
  • Allow words that can use letters from at most two rows instead of strictly one.
  • Adapt the solution for different keyboard layouts, such as Dvorak or QWERTZ.

FAQ

What pattern does the Keyboard Row problem follow?

It follows an Array scanning plus hash lookup pattern where each word is verified against a precomputed hash map of keyboard rows.

How does case-insensitivity affect the solution?

All letters should be converted to lowercase before checking the row, ensuring uppercase letters are treated correctly.

Can this solution handle large word lists?

Yes, because the time complexity scales linearly with the total number of letters across all words, making it efficient for small to medium lists.

Why use a hash map instead of a simple array?

A hash map allows O(1) lookup for each letter, which ensures efficient row verification for each word without scanning rows repeatedly.

What is the key failure mode to avoid in Keyboard Row?

The main failure mode is missing letters from different rows within a word, so every letter must be checked against the row hash to avoid false positives.

terminal

Solution

Solution 1

#### Python3

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def findWords(self, words: List[str]) -> List[str]:
        s1 = set('qwertyuiop')
        s2 = set('asdfghjkl')
        s3 = set('zxcvbnm')
        ans = []
        for w in words:
            s = set(w.lower())
            if s <= s1 or s <= s2 or s <= s3:
                ans.append(w)
        return ans

Solution 2

#### Python3

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def findWords(self, words: List[str]) -> List[str]:
        s1 = set('qwertyuiop')
        s2 = set('asdfghjkl')
        s3 = set('zxcvbnm')
        ans = []
        for w in words:
            s = set(w.lower())
            if s <= s1 or s <= s2 or s <= s3:
                ans.append(w)
        return ans
Keyboard Row Solution: Array scanning plus hash lookup | LeetCode #500 Easy