Problem Description
Given an array of words, return the words that can be typed using letters of the alphabet on only one row of an American keyboard. The solution must be case-insensitive, meaning both uppercase and lowercase representations of a letter are considered equivalent. The American keyboard layout has three rows: the first row is "qwertyuiop", the second row is "asdfghjkl", and the third row is "zxcvbnm".
Key Insights
- Convert each word to a consistent case (lowercase) for uniform processing.
- Predefine sets for the three keyboard rows.
- For each word, determine if all its characters belong to a single keyboard row by checking if the set of characters is a subset of one of the row sets.
- Use set operations for an efficient subset check.
Space and Time Complexity
Time Complexity: O(n * m) where n is the number of words and m is the maximum length of a word, since each word's characters are checked. Space Complexity: O(1) in terms of extra space aside from the output list, as the keyboard row sets require constant space.
Solution
The algorithm works by first creating three sets representing the letters in each row of the American keyboard. Then, for each word in the input, we convert it to lowercase and create a set of its characters. By checking if this set is a subset of any one of the three row sets, we can decide whether the word can be typed using only one row. If the condition is met, the word is added to the result list.