Valid Anagram⚓︎
Description⚓︎
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
- Input:
s = "anagram",t = "nagaram" - Output:
true
Example 2:
- Input:
s = "rat",t = "car" - Output:
false
Constraints:
1 <= s.length,t.length <= 5 * 10^4sandtconsist of lowercase English letters.
Solution⚓︎
Hash Map⚓︎
- Assuming that the string contains only lowercase letters, use an array of length 26 as a hash table to keep track of the number of times a letter appears.
- For
s, add the number of letters to the hash table. - For
t, reduce the number of corresponding letters in the hash table. - Finally, from
atozstatistics whether there is not 0 cases, if so, then return false, otherwise return true.
Hash Map (Simpler)⚓︎
Time complexity: \(O(n)\)