Keyboard Row Solution in Python


Problem Description

So, you think you can type? Well, let’s put that to the test! The “Keyboard Row” problem on LeetCode is like a game of musical chairs, but instead of chairs, we have rows of keys on a keyboard. The challenge is to find out which words can be typed using letters from just one row of the keyboard.

Imagine you’re at a party, and you can only dance with people from your row. If someone from another row tries to join, well, they’re just not invited! Similarly, in this problem, if a word contains letters from more than one row, it’s not allowed to join the party.

Code Solution


class Solution:
    def findWords(self, words: list[str]) -> list[str]:
        ans = []
        rows = [set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')]

        for word in words:
            lowerWord = set(word.lower())
            if any(lowerWord <= row for row in rows):
                ans.append(word)

        return ans

Approach

The approach taken in this solution is straightforward yet effective. It uses sets to represent each row of the keyboard. For each word, it converts the word to lowercase and checks if all its letters belong to any one of the three sets (rows). If they do, the word is added to the answer list.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(N * M), where N is the number of words and M is the maximum length of a word.
Space Complexity O(1) for the rows since they are constant, and O(K) for the output list, where K is the number of valid words.

Real-World Example

Think of it this way: you’re at a keyboard convention, and you can only hang out with people who use the same keyboard layout as you. If you’re a QWERTY user, you can only chat with other QWERTY users. If someone starts talking about Dvorak or AZERTY, you just roll your eyes and walk away. This problem is all about finding those exclusive QWERTY friends!

Similar Problems

If you enjoyed this problem, you might also like these: