Given a list of words, return the words that can be typed using letters of the alphabet on only one row of the American keyboard.
The American keyboard layout has the following rows:
You need to determine which words can be typed using letters from only one of these rows.
Data Structures: Use sets to store the characters from each row of the keyboard. Sets will allow for fast membership testing.
Normalize Case: Convert each word to lowercase to handle case insensitivity.
Check Membership: For each word, check if all characters belong to one of the sets. This can be done using set operations in Python.
Result Collection: Collect and return words that meet the criteria.
def findWords(words):
# Define sets for each keyboard row
row1 = set("qwertyuiop")
row2 = set("asdfghjkl")
row3 = set("zxcvbnm")
result = []
for word in words:
# Convert word to lowercase for case insensitivity
lower_word = word.lower()
# Convert the word to a set of unique characters
word_set = set(lower_word)
# Check if the set of characters is a subset of any of the rows
if word_set <= row1 or word_set <= row2 or word_set <= row3:
result.append(word)
return result
# Example Usage:
words_list = ["Hello", "Alaska", "Dad", "Peace"]
print(findWords(words_list)) # Output: ['Alaska', 'Dad']
The provided solution is efficient and should handle typical constraints comfortably. Do let me know if you have further questions or need additional use cases!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?