Keyboard Row - Hash Table - Easy - LeetCode
💻 coding

Keyboard Row - Hash Table - Easy - LeetCode

1 min read 149 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to identify words that can be typed using letters from only one row of the American keyboard.
  • 2An example input is ['Hello', 'Alaska', 'Dad', 'Peace'], with the output being ['Alaska', 'Dad'].
  • 3The solution involves mapping keyboard rows to characters and checking each word against these mappings.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to identify words that can be typed using letters from only one row of the American keyboard."

Keyboard Row - Hash Table - Easy - LeetCode

Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.

Example:

Input: ["Hello", "Alaska", "Dad", "Peace"] Output: ["Alaska", "Dad"]

Note:

You may use one character in the keyboard more than once. You may assume the input string will only contain letters of alphabet.

public class Solution {
 public string[] FindWords(string[] words) {
 if(words.Length==0){
 return words;
 }
 
 var strArr = new string[]{"qwertyuiop", "asdfghjkl", "zxcvbnm"};
 var map = new Dictionary<char,int>();
 for(int i=0;i<strArr.Length;i++){
 for(int j=0;j<strArr[i].Length;j++){
 map.Add(strArr[i][j],i);
 }
 }
 
 var result = new List<string>();
 for(int i=0;i<words.Length;i++){
 var str =words[i].ToLower();
 int index = map[str[0]];
 bool found = true;
 for(int j=1;j<str.Length;j++){
 if(map[str[j]]!=index){
 found = false;
 break;
 }
 } 
 if(found){
 result.Add(words[i]);
 } 
 }
 
 return result.ToArray();
 }
}

Time Complexity: O(m*n)

Space Complexity: O(m*n)

Where m is the number of strings and n is the maximum character in the string.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 28 September 2020 · 1 min read · 149 words

Part of AskGif Blog · coding

You might also like