Problem Solving
[Leetcode] 242. Valid Anagram
leeyngdo
2023. 7. 13. 18:14
Problem Link: https://leetcode.com/problems/valid-anagram/
Valid Anagram - LeetCode
Can you solve this real interview question? Valid Anagram - 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
leetcode.com
Solution 1. Hash Table (Iteration)
Time: $O(N)$
Space: $O(N)$

class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
freq_s = dict()
freq_t = dict()
if len(s) != len(t):
return False
for x, y in zip(s, t):
freq_s[x] = freq_s.get(x, 0) + 1
freq_t[y] = freq_t.get(y, 0) + 1
while freq_s:
key, val = freq_s.popitem()
if not (key in freq_t) or val != freq_t[key]:
return False
return True