Valid Anagram
- 1 min read
- Array
- String
- LC-Easy
Solution
- Can solve in multiple different ways
- Uber simple 1 liner:
return Counter(s) == Counter(t) - Have hashmap of counts, iterate through hashmap, if freq. does not match, return False
- Instead of hashmap, can also utilizie char array of length 26 but it's basically the same thing
| Time | Space | Explanation |
|---|
O(s + t) | O(1) | Space is constant because charset is constant |
HashMap Soln.
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
sc, tc = defaultdict(lambda: 0), defaultdict(lambda: 0)
for i in range(len(s)):
sc[s[i]] += 1
tc[t[i]] += 1
for ch in sc:
if sc[ch] != tc[ch]:
return False
return True
Counter Soln.
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
counts = [0] * 26
for i in range(len(s)):
counts[ord(s[i]) - ord('a')] += 1
counts[ord(t[i]) - ord('a')] -= 1
return counts.count(0) == 26`
One-Liner
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)