Tuesday, January 28, 2025

Valid Anagram

Profile Pic of Akash AmanAkash Aman

Updated: January 2025

Valid Anagram
easy

💡 Intuition

  • By sorting both strings, we can compare their characters at each index. If both strings are valid anagrams, their sorted forms will match. This approach has a time complexity of O(n log n) for sorting and (O(n)) for comparison, resulting in an overall complexity of O(n log n).

"nagaram""anagram""aaagmnr""aaagmnr"SortSortCompare


  • Alternatively, we can count the occurrences of each character in the first string and compare it with the character counts in the second string. This involves one loop to count characters and another loop to validate the counts, giving a time complexity of ( O(n + n) = O(n) ).

anagramanagramanagramanagramanagramanagramanagramanagramanagramanagramanagramanagramanagramanagramIteration 1Iteration 2Iteration 3Iteration 4Iteration 5Iteration 6Iteration 7+1-1+1-1+1-1+1-1+1-1+1-1+1-1anngangangangangaWe are incrementing 1 for each char for first string and decrementing 1 for each char for second string.In this way if the count of each char in both string are same, the end map with all the char should have result 0Mapan1-100rrrm0-110000000000000000Update count of charUpdate count of charUpdate count of charUpdate count of charUpdate count of charUpdate count of charUpdate count of charIteration results are the end result of any specific iteration


🚀 Solution

go
func isAnagram(s string, t string) bool { set := map[rune]int{}; if len(s) != len(t) { return false; } tRune := []rune(t); for index,sChar := range []rune(s) { if _,ok := set[sChar]; !ok { set[sChar] = 1; } else { set[sChar] = set[sChar] + 1; } if _, ok := set[tRune[index]]; !ok { set[tRune[index]] = -1; } else { set[tRune[index]] = set[tRune[index]] - 1; } } for _,val := range set { if val != 0 { return false; } } return true; }

⏳ Time Complexity

  • Since we are taking single loop for the array of length n, the time complexity will be O(n)