π Introduction
Given an array of strings, return the words that can be typed using letters of the alphabet on only one row of a standard American keyboard.
The keyboard rows are: Top row: qwertyuiop Middle row: asdfghjkl Bottom row: zxcvbnm
You may return the answer in any order.
π‘ Approach & Key Insights
The main idea is to check for each word if all its characters belong to the same keyboard row. By converting each word to lowercase and then to a set, we can easily determine if its characters are a subset of any one row.
π οΈ Breakdown of Approaches
1οΈβ£ Brute Force / Naive Approach
- Explanation: For each word, check if every character belongs to the same keyboard row by comparing each character to the characters in all three rows. This involves checking character-by-character for each word.
- Time Complexity: O(n * m) - where n is the number of words and m is the average length of each word.
- Space Complexity: O(1) - ignoring output space.
- Example/Dry Run:
Example input: ["Hello", "Alaska", "Dad", "Peace"]
"Hello" β uses letters from multiple rows β β"Alaska" β only row 2 β β"Dad" β only row 2 β β"Peace" β multiple rows β β
Output: ["Alaska", "Dad"]
2οΈβ£ Optimized Approach
- Explanation: Instead of checking characters one by one, convert each row into a set. Then convert the word into a lowercase set and check if itβs a subset of any of the three row sets.
- Time Complexity: O(n * m) - where n is the number of words and m is the average length of the words. Checking issubset is efficient for set comparisons.
- Space Complexity: O(1) - excluding the space for the output list.
- Example/Dry Run:
Example input: ["Hello", "Alaska", "Dad", "Peace"]
Step 1 β Convert keyboard rows into setsStep 2 β For each word, convert to lowercase setStep 3 β Check if set is subset of row1, row2, or row3
Output: ["Alaska", "Dad"]
3οΈβ£ Best / Final Optimized Approach (if applicable)
- Explanation: The current solution is optimal for this problem. Using sets makes subset checking straightforward and efficient.
- Time Complexity: O(n * m)
- Space Complexity: O(1)
- Example/Dry Run:
Input: ["Type", "Row", "Zzz"]
"Type" β mixed rows β β"Row" β row 1 β β"Zzz" β row 3 β β
Output: ["Row", "Zzz"]
π Complexity Analysis
Approach | Time Complexity | Space Complexity |
---|---|---|
Brute Force | O(n * m) | O(1) |
Optimized | O(n * m) | O(1) |
Best Approach | O(n * m) | O(1) |
π Optimization Ideas
You could pre-map each letter to its row number and then verify if all characters in a word belong to the same row number. This might slightly improve runtime in practice, but the set-based method is already clean and efficient.
π Example Walkthroughs & Dry Runs
Example:Input: ["Alaska", "Dad", "Peace"]
Process:1. Alaska β to lower β "alaska" β set("alaska") = {'a', 'l', 's', 'k'} β row2 β β2. Dad β "dad" β {'d', 'a'} β row2 β β3. Peace β "peace" β {'p', 'e', 'a', 'c'} β any row β β
Output: ["Alaska", "Dad"]
π Additional Resources
Author: Daniel Nallapalli Date: 16/06/2025