↓Skip to main content
  1. LeetCode/

LeetCode 500: Keyboard Row

·1 min· ·
LeetCode Easy Array Hash-Table String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-25

  • Submissions: Accepted (first try)

Approach
#

Make each keyboard row a set (Hash Table); a word whose lowercase character set is a subset (<=) of one row can be typed on that row. Case does not matter.

My Solution
#

class Solution:
    def findWords(self, words: List[str]) -> List[str]:
        rows = [set("qwertyuiop"), set("asdfghjkl"), set("zxcvbnm")]
        return [w for w in words if any(set(w.lower()) <= r for r in rows)]

Complexity
#

Time O(total characters), space O(1).

Mistakes to Avoid
#

  • Lowercase before comparing.
  • Keep the original case and order in the output.

Interview Explanation
#

I make each keyboard row a set and keep words whose lowercase characters form a subset of one row, in time linear in the total length.

Related

LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them
LeetCode 350: Intersection of Two Arrays II
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 note: an intersection keeping multiplicity, where Counter’s & takes the smaller count from each side
LeetCode 448: Find All Numbers Disappeared in an Array
·1 min
LeetCode Easy Array Hash-Table
LeetCode 448 note: use the array itself as the hash table, marking nums[x - 1] negative for each x; positions still positive are the missing numbers
LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 290: Word Pattern
·1 min
LeetCode Easy Hash-Table String
LeetCode 290 note: pattern characters and words must correspond one to one; use two dicts or compare set sizes
LeetCode 383: Ransom Note
·1 min
LeetCode Easy Hash-Table String Counting
LeetCode 383 note: every character’s demand in ransomNote must not exceed its supply in magazine; an empty Counter difference means yes