Valid Anagram - Hash Table - Easy - LeetCode
💻 coding

Valid Anagram - Hash Table - Easy - LeetCode

1 min read 151 words
1 min read
ShareWhatsAppPost on X
  • 1The function determines if one string is an anagram of another by comparing character counts.
  • 2It uses two hash tables to store character frequencies from both strings.
  • 3The solution has a time complexity of O(n) and a space complexity of O(n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The function determines if one string is an anagram of another by comparing character counts."

Valid Anagram - Hash Table - Easy - LeetCode

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram" Output: true Example 2:

Input: s = "rat", t = "car" Output: false Note: You may assume the string contains only lowercase alphabets.

Follow up: What if the inputs contain unicode characters? How would you adapt your solution to such case?

public class Solution {
 public bool IsAnagram(string s, string t) {
 if(s.Length != t.Length){
 return false;
 }
 var map1 = new Dictionary<char,int>();
 var map2 = new Dictionary<char,int>();
 for(int i=0;i<s.Length;i++){
 if(map1.ContainsKey(s[i])){
 map1[s[i]]++;
 }
 else{
 map1.Add(s[i],1);
 }
 
 if(map2.ContainsKey(t[i])){
 map2[t[i]]++;
 }
 else{
 map2.Add(t[i],1);
 }
 }
 
 foreach(var item in map1){
 if(!map2.ContainsKey(item.Key)){
 return false;
 }
 
 if(item.Value != map2[item.Key]){
 return false;
 }
 }
 
 foreach(var item in map2){
 if(!map1.ContainsKey(item.Key)){
 return false;
 }
 
 if(item.Value != map1[item.Key]){
 return false;
 }
 }
 
 return true;
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

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

Part of AskGif Blog · coding

You might also like