Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
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:
"qwertyuiop","asdfghjkl", and"zxcvbnm".Example 1:
Input: words = ["Hello","Alaska","Dad","Peace"]
Output: ["Alaska","Dad"]
Explanation:
Both "a" and "A" are in the 2nd row of the American keyboard due to case insensitivity.
Example 2:
Input: words = ["omk"]
Output: []
Example 3:
Input: words = ["adsdf","sfd"]
Output: ["adsdf","sfd"]
Constraints:
1 <= words.length <= 201 <= words[i].length <= 100words[i] consists of English letters (both lowercase and uppercase). Problem summary: 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".
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
["Hello","Alaska","Dad","Peace"]
["omk"]
["adsdf","sfd"]
find-the-sequence-of-strings-appeared-on-the-screen)find-the-original-typed-string-i)find-the-original-typed-string-ii)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #500: Keyboard Row
class Solution {
public String[] findWords(String[] words) {
String s = "12210111011122000010020202";
List<String> ans = new ArrayList<>();
for (var w : words) {
String t = w.toLowerCase();
char x = s.charAt(t.charAt(0) - 'a');
boolean ok = true;
for (char c : t.toCharArray()) {
if (s.charAt(c - 'a') != x) {
ok = false;
break;
}
}
if (ok) {
ans.add(w);
}
}
return ans.toArray(new String[0]);
}
}
// Accepted solution for LeetCode #500: Keyboard Row
func findWords(words []string) (ans []string) {
s := "12210111011122000010020202"
for _, w := range words {
x := s[unicode.ToLower(rune(w[0]))-'a']
ok := true
for _, c := range w[1:] {
if s[unicode.ToLower(c)-'a'] != x {
ok = false
break
}
}
if ok {
ans = append(ans, w)
}
}
return
}
# Accepted solution for LeetCode #500: Keyboard Row
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
// Accepted solution for LeetCode #500: Keyboard Row
struct Solution;
use std::collections::HashMap;
impl Solution {
fn find_words(words: Vec<String>) -> Vec<String> {
let rows: Vec<String> = [
"qwertyuiopQWERTYUIOP",
"asdfghjklASDFGHJKL",
"zxcvbnmZXCVBNM",
]
.iter()
.map(|v| (*v).to_string())
.collect();
let mut hm: HashMap<char, usize> = HashMap::new();
for i in 0..3 {
let row = &rows[i];
for c in row.chars() {
hm.insert(c, i);
}
}
let mut res: Vec<String> = vec![];
for word in words {
let rows: Vec<usize> = word.chars().map(|c| *hm.get(&c).unwrap()).collect();
if rows.windows(2).all(|w| w[0] == w[1]) {
res.push(word);
}
}
res
}
}
#[test]
fn test() {
let words: Vec<String> = vec_string!["Hello", "Alaska", "Dad", "Peace"];
let res: Vec<String> = vec_string!["Alaska", "Dad"];
assert_eq!(Solution::find_words(words), res);
}
// Accepted solution for LeetCode #500: Keyboard Row
function findWords(words: string[]): string[] {
const s = '12210111011122000010020202';
const ans: string[] = [];
for (const w of words) {
const t = w.toLowerCase();
const x = s[t.charCodeAt(0) - 'a'.charCodeAt(0)];
let ok = true;
for (const c of t) {
if (s[c.charCodeAt(0) - 'a'.charCodeAt(0)] !== x) {
ok = false;
break;
}
}
if (ok) {
ans.push(w);
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.