Neetcode 150 - Valid Anagram

1. Sorting

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

        return sorted(s) == sorted(t)
  • Time comlexity: O(nlogn + mlogm)

  • Space Complexity: O(1) or O(n + m).

2. Hash Map

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

        countS, countT = {}, {}

        for i in range(len(s)):
            countS[s[i]] = 1 + countS.get(s[i], 0)
            countT[t[i]] = 1 + countT.get(t[i], 0)

        return countS == countT

  • Time comlexity: O(n + m)

  • Space Complexity: O(26)

3. Hash Table (An Array work as a table)

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

        count = [0] * 26
        for i in range(len(s)):
            count[ord(s[i]) - ord('a')] += 1
            count[ord(t[i]) - ord('a')] -= 1

        for val in count:
            if val != 0:
                return False

        return True
  • Time comlexity: O(n + m)

  • Space Complexity: O(26)

Last Updated On October 22, 2025