Given two strings s and t , write a function to determine if t is an anagram of s.
An anagram is a result of rearranging the letters of a word to produce a new word.
Input: s = "anagram", t = "nagaram"
Output: true
Input: s = "rat", t = "car"
Output: false
You may assume the string contains only lowercase alphabets.
What if the inputs contain unicode characters? How would you adapt your solution to such case?
- use an array of size 26, to count the frequency of each alphabet
- sweep through first string and increment the count for each alphabet
- sweep through second string and decrement the count for each alphabet
- check the counter array, if every value in the array is 0, then the strings are an anagram
-
Time complexity :
O(len(string))
. We have to sweep through the entire string. -
Space complexity :
O(1)
. The size of the counter array is always 26. Does not scale with the size of the string.
- Count the frequency of each character in first string. ( use hashmap )
O(n)
- For Second string, check if each character in the string
O(n)
exists in the hashmapO(1)
- If yes,
O(1)
- If count is already 0. Then its not an anagram.
- Else, decrement the count by 1
- If no, Then its not an anagram.
O(n)
- If yes,
-
Time complexity :
O(len(string))
. We have to sweep through the entire string. -
Space complexity :
O(len(string))
. The size of the hashmap, to fit in all the unicode characters present it. in worst case, when every character is unique, the space becomeslen(string)