Blogs Hub

Keyboard Row - Hash Table - Easy - LeetCode - MiniTV

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.