LeetcodeJan 03, 2026

Keyboard Row

Hazrat Ali

Leetcode

Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.

Note that the strings are case-insensitive, both lowercased and uppercased of the same letter are treated as if they are at the same row.

In the American keyboard:

  • the first row consists of the characters "qwertyuiop",
  • the second row consists of the characters "asdfghjkl", and
  • the third row consists of the characters "zxcvbnm".

 

Example 1:

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

Output: ["Alaska","Dad"]

 

Solution

var findWords = function(words) {
    const row1 = new Set("qwertyuiop");
    const row2 = new Set("asdfghjkl");
    const row3 = new Set("zxcvbnm");

    const result = [];

    for (let word of words) {
        const lower = word.toLowerCase();
        let row;

        if (row1.has(lower[0])) row = row1;
        else if (row2.has(lower[0])) row = row2;
        else row = row3;

        let valid = true;
        for (let ch of lower) {
            if (!row.has(ch)) {
                valid = false;
                break;
            }
        }

        if (valid) result.push(word);
    }

    return result;
};

 

 

Comments