Keyboard Row

easy array hash map string

Problem

Given an array of strings words, return the words that can be typed using letters from only one row of an American QWERTY keyboard.

Inputwords = ["Hello", "Alaska", "Dad", "Peace"]
Output["Alaska", "Dad"]
Alaska uses only middle row, Dad uses only middle row.

def find_words(words):
    rows = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
    letter_row = {}
    for i, r in enumerate(rows):
        for ch in r: letter_row[ch] = i
    out = []
    for w in words:
        lw = w.lower()
        if len({letter_row[ch] for ch in lw}) == 1:
            out.append(w)
    return out
function findWords(words) {
  const rows = ["qwertyuiop", "asdfghjkl", "zxcvbnm"];
  const letterRow = {};
  rows.forEach((r, i) => { for (const c of r) letterRow[c] = i; });
  return words.filter(w => {
    const lw = w.toLowerCase();
    const seen = new Set();
    for (const c of lw) seen.add(letterRow[c]);
    return seen.size === 1;
  });
}
class Solution {
    public String[] findWords(String[] words) {
        String[] rows = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};
        int[] map = new int[26];
        for (int i = 0; i < rows.length; i++)
            for (char c : rows[i].toCharArray()) map[c - 'a'] = i;
        List<String> out = new ArrayList<>();
        for (String w : words) {
            String lw = w.toLowerCase();
            int row = map[lw.charAt(0) - 'a'];
            boolean ok = true;
            for (char c : lw.toCharArray()) if (map[c - 'a'] != row) { ok = false; break; }
            if (ok) out.add(w);
        }
        return out.toArray(new String[0]);
    }
}
vector<string> findWords(vector<string>& words) {
    string rows[3] = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};
    int map[26];
    for (int i = 0; i < 3; i++) for (char c : rows[i]) map[c - 'a'] = i;
    vector<string> out;
    for (auto& w : words) {
        int row = map[tolower(w[0]) - 'a'];
        bool ok = true;
        for (char c : w) if (map[tolower(c) - 'a'] != row) { ok = false; break; }
        if (ok) out.push_back(w);
    }
    return out;
}
Time: O(Σ|w|) Space: O(1) (constant 26-letter map)