Keyboard Row - Problem

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.

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"
  • The third row consists of the characters "zxcvbnm"

Input & Output

Example 1 — Mixed Rows
$ Input: words = ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
💡 Note: "Alaska" uses only row 1 letters (a,s,k), "Dad" uses only row 2 letters (d,a). "Hello" and "Peace" use multiple rows.
Example 2 — Single Character
$ Input: words = ["omk"]
Output: []
💡 Note: "omk" contains 'o' (row 1), 'm' (row 3), 'k' (row 2) - uses all three keyboard rows, so not included.
Example 3 — Case Insensitive
$ Input: words = ["adsdf", "sfd"]
Output: ["adsdf", "sfd"]
💡 Note: Both words use only row 2 letters (a,d,s,f). Case doesn't matter as stated in problem.

Constraints

  • 1 ≤ words.length ≤ 20
  • 1 ≤ words[i].length ≤ 100
  • words[i] consists of English letters.

Visualization

Tap to expand
Keyboard Row Problem INPUT words array: "Hello" "Alaska" "Dad" "Peace" American Keyboard Rows: qwertyuiop (Row 1) asdfghjkl (Row 2) zxcvbnm (Row 3) ALGORITHM STEPS 1 Build Hash Map Map each letter to row q,w,e,r,t,y,u,i,o,p --> 1 a,s,d,f,g,h,j,k,l --> 2 z,x,c,v,b,n,m --> 3 2 Check Each Word Convert to lowercase 3 Verify Same Row All chars same row? "Hello": h(2),e(1) - NO "Alaska": all row 2 - OK "Dad": all row 2 - OK "Peace": p(1),e(1),a(2) - NO 4 Return Valid Words Collect passing words FINAL RESULT Words typed on single row: "Alaska" Row 2: a,s,d,f,g,h,j,k,l "Dad" Row 2: a,s,d,f,g,h,j,k,l Output Array: ["Alaska", "Dad"] 2 words found! Key Insight: Hash Map Lookup Use a hash map to store each letter's keyboard row (1, 2, or 3). For each word, check if all characters map to the same row number. Time: O(n*m) where n = words, m = avg word length. Space: O(26) = O(1) for the character-to-row mapping. TutorialsPoint - Keyboard Row | Hash Map Lookup Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
28.5K Views
Medium Frequency
~15 min Avg. Time
842 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen