Valid Anagram

Easy

Topics
StringHash TableSorting

Given two strings s and t, return true if t is an anagram of s (same letters, same counts).

Example 1

sanagram
tnagaram
Both strings use the same letters the same number of times, so the answer is true.
Rows are the two strings, character by character.
Input:  s = "anagram", t = "nagaram"
Output: true

Example 2

srat
tcar
The shaded characters in t have no counterpart left in s, so the answer is false. A length mismatch alone is already enough to decide it.
Input:  s = "rat", t = "car"
Output: false

Constraints

  • 1 <= s.length, t.length <= 5*10^4
  • s and t consist of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Two strings are anagrams exactly when they contain the same multiset of characters. Comparing their character-frequency counts settles it.

Approach

  1. Different lengths → not anagrams.
  2. Count characters of s.
  3. Decrement while scanning t; a missing or over-used character means false.
  4. If all counts balance, they are anagrams.

Walkthrough

s = "anagram", t = "nagaram"
count(s) = {a:3, n:1, g:1, r:1, m:1}
count(t) = {n:1, a:3, g:1, r:1, m:1}  -> equal -> true

Complexity

  • Time — O(n): counting both strings is linear.
  • Space — O(1): the count map is bounded by the alphabet (26 lowercase letters).

Common Pitfalls

  • For Unicode input, a fixed 26-size array no longer suffices — use a hash map.

Full Solution — all languages

class Solution:
    def isAnagram(self, s, t):
        if len(s) != len(t):
            return False
        counts = {}
        for c in s:
            counts[c] = counts.get(c, 0) + 1
        for c in t:
            if counts.get(c, 0) == 0:
                return False
            counts[c] -= 1
        return True
SensAI
Beta
Tap the mic to stop voice mode