Question

Restate the problem

Anagram: same character, same frequency, different order

  • Given two strings s and t
  • Return true if t is an anagram of s, return false if not anagram.

Edge Case

  • s = [aaa], t = [aa] False, different frequency
  • s = [], t = [] True

MethodApproachTime ComplexitySpace Complexity
Method 1 ⭐HashmapO(n)O(k)
Method 2SortO()O(n)

Method 1 - Hashmap

Approach

  • Compare the s length and t length, if not, return False
  • Counter s, count = {char: frequency}
  • For each characterc in t
    • If c not in count or count is 0, return False
    • Decrement count
  • return True

Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(k)
    • k = number of distinct characters in s

Code

from collections import Counter
 
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
 
        counter = Counter(s)
        
        for char in t:
            if counter[char] < 1:
                return False
            counter[char] -= 1
        
        return True

Method 2 - Sort

Complexity

  • Time Complexity: O()
  • Space Complexity: O(n)

Code

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

Mistake:

  • list.sort() works in-place, strings are immutable, cannot use .sort().

History

  • Feb-27-2026 Solved