# 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

`.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}qsd -> 0112asd -> 111`

Use set for faster check

`1qsdx -> 0112 -> Set(0, 1, 2) -> invalid2asdf -> 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] = rowIndex6    }7    return map8  }, {})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 === 116  })17}```

leetcode

array

string

hash table

## Next Post

LeetCode: Maximum Average Subarray I

Sep 10, 2021

Find maximum sum of contiguous subarray with length of K

## Previous Post

LeetCode: Array Partition I

Sep 7, 2021

Sometimes, don't analyse

Search Posts