LeetCode: Keyboard Row Solution

Duck-typing make this problem less hard to implement

Approach

Create a hash table with key-value pair of character-row (eg. q->0, a->1, z-2)

Map each word's characters to the relevant rows and choose the one that only created from one row

1qsd -> 011
2asd -> 111

Use set for faster check

1qsdx -> 0112 -> Set(0, 1, 2) -> invalid
2asdf -> 1111 -> Set(1) -> valid

Implementation

1var findWords = function (words) {
2 const rowChars = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
3 const charRowMap = rowChars.reduce((map, row, rowIndex) => {
4 for (const char of row) {
5 map[char] = rowIndex
6 }
7 return map
8 }, {})
9
10 return words.filter(word => {
11 const set = new Set()
12 for (const char of word.toLowerCase()) {
13 set.add(charRowMap[char])
14 }
15 return set.size === 1
16 })
17}

Comments

Loading comments...

Tags

leetcode

array

string

hash table

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Maximum Average Subarray I

Find maximum sum of contiguous subarray with length of K

Previous Post

LeetCode: Array Partition I

Sometimes, don't analyse

HoningJS

Search Posts