Notes

Personal notes on various topics

View on GitHub

Intuition

To check if two strings are anagrams, we need to verify that both strings contain the same characters with the same frequencies.

Approach

Complexity

Code

from collections import Counter

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False

        t_count = Counter(t)
        for c in s:
            if c in t_count:
                t_count[c] -= 1

        for k, v in t_count.items():
            if v != 0:
                return False

        return True

Back to Problem Statement