Valid Anagram (Leetcode #242)
Question:
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<sup>4</sup>
s
andt
consist of lowercase English letters.
Answer:
Algorithm:
Check if the length of the two words is the same if it isn't then we can add an early exit clause
Create a hashmap of the count of characters of the two words then if the two hashmap are the same return True
s_count = {}
t_count = {}
if len(s) != len(t):
return False
for i in range(len(s)):
s_count[s[i]] = 1+s_count.get(s[i],0)
t_count[t[i]] = 1+t_count.get(t[i],0)
return s_count == t_count
Time complexity
O(N) Since we have through every character ounce
Space Complexity
O(N) Since we have to create a hashmap for each word. But is this the best we can do with the space complexity?
Optimize Solution
We know that S and T only contain lower English characters, hence we can create a list to count using list and we know that the size of the list will be 26 which will give us constant space complexity O(1)
s_count = [0]*26
t_count = [0]*26
if len(s) != len(t):
return False
for i in range(len(s)):
s_count[ord(s[i]) - ord('a')] += 1
t_count[ord(t[i]) - ord('a')] += 1
return s_count == t_count
This will give us the time complexity of O(N) and the time complexity of O(1)