Solving Leetcode Interviews in Seconds with AI: Keyboard Row
Introduction
In this blog post, we will explore how to solve the LeetCode problem "500" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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. In the American keyboard: the first row consists of the characters "qwertyuiop", the second row consists of the characters "asdfghjkl", and the third row consists of the characters "zxcvbnm". Example 1: Input: words = ["Hello","Alaska","Dad","Peace"] Output: ["Alaska","Dad"] Explanation: Both "a" and "A" are in the 2nd row of the American keyboard due to case insensitivity. Example 2: Input: words = ["omk"] Output: [] Example 3: Input: words = ["adsdf","sfd"] Output: ["adsdf","sfd"] Constraints: 1 <= words.length <= 20 1 <= words[i].length <= 100 words[i] consists of English letters (both lowercase and uppercase).
Explanation
Here's a breakdown of the solution:
- Row Identification: Create sets representing the characters on each keyboard row.
- Word Check: For each word, determine if all its characters belong to the same row.
Filtering: Return the words that satisfy the single-row condition.
Runtime Complexity: O(N M) where N is the number of words and M is the maximum length of a word. *Storage Complexity: O(1), because the row sets are constant size.
Code
def findWords(words):
row1 = set("qwertyuiop")
row2 = set("asdfghjkl")
row3 = set("zxcvbnm")
result = []
for word in words:
lower_word = word.lower()
first_char_row = None
if lower_word[0] in row1:
first_char_row = row1
elif lower_word[0] in row2:
first_char_row = row2
else:
first_char_row = row3
valid = True
for char in lower_word:
if char not in first_char_row:
valid = False
break
if valid:
result.append(word)
return result