Skip to main content
Easy Hash Map / Set High frequency

Valid Anagram

Open on LeetCode

Approach Summary

Count character frequencies in s, decrement for t. If all counts are 0, they are anagrams.

Full Solution & Approach

Two strings are anagrams if they contain the same characters with the same frequencies. The shortest path is to sort both and compare — O(n log n) and trivial but not optimal. Better: count character frequencies with a hash map in one pass over s, then decrement over t. If t ever references a character not in the map, or a count already at 0, it has a character s does not — return false. At the end every count must have been decremented back to 0, so the map must be empty. This is O(n) time and O(1) space in practice because the alphabet is bounded (26 lowercase letters or 128 ASCII). The frequency-counter pattern is the workhorse behind almost every anagram and permutation-in-string problem on LeetCode, so it is worth internalizing over the sort shortcut.

Two linear passes with O(1) hash operations per character — O(n) time. The map holds at most the alphabet size — bounded constant space.

Solution Code

Solution

from collections import Counter

def is_anagram(s: str, t: str) -> bool:
    return Counter(s) == Counter(t)

Edge Cases to Watch

  • Different lengths — immediately false
  • Empty strings — true
  • Unicode characters — the map keys on any character, so any alphabet works
  • Repeated characters — the count-based check is exact

How to Recognize This Pattern

  • Check if two strings contain same characters

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)

Tags

String Hash Map Sorting

This site is free. If these guides are helping your prep, consider buying me a coffee. ☕

Support →
Buy me a coffee