Keyboard Row — LeetCode 500 Python Solution

EasyArrayHash TableString
Problem
#500
Pattern
Hash Map
Reading time
2 min

The 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 like the image below. 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.

Python solution

Python
class Solution:
    def findWords(self, words: List[str]) -> List[str]:
        s1 = set('qwertyuiop')
        s2 = set('asdfghjkl')
        s3 = set('zxcvbnm')
        ans = []
        for w in words:
            s = set(w.lower())
            if s <= s1 or s <= s2 or s <= s3:
                ans.append(w)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 500. Keyboard Row is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 500. Keyboard Row?
LeetCode 500. Keyboard Row is rated Easy on LeetCode.
What is the time complexity of LeetCode 500. Keyboard Row?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 500. Keyboard Row?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 500. Keyboard Row cover?
LeetCode 500. Keyboard Row is tagged Array, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview