Back to the 100
Problem 003Arrays & Hashing
Easy

Valid Anagram

003

Given two strings s and t, return true if t is an anagram of s, and false otherwise. An anagram uses every character from the original string exactly once.

EXAMPLES

Example 1
Input
{
  "s": "anagram",
  "t": "nagaram"
}

Output
true

FUNCTION SHAPE

s: stringt: stringbool
SOLUTION NOTE

There are a few ways to do this using sorting and counters. The O(n log n) sorting approach is also valid.

Reveal reference solution +
pythonREFERENCE
# Method 1: Compare sorted counters
def isAnagram(self, s: str, t: str) -> bool:
    return sorted(Counter(s).items()) == sorted(Counter(t).items())

# Method 2: Compare sorted strings
def isAnagram(self, s: str, t: str) -> bool:
    return sorted(s) == sorted(t)

# Method 3: Compare counters directly
def isAnagram(self, s: str, t: str) -> bool:
    return Counter(s) == Counter(t)

# Method 4: Decrement counter
def isAnagram(self, s: str, t: str) -> bool:
    freq = Counter(s)
    for c in t:
        freq[c] -= 1
        if freq[c] == 0:
            del freq[c]
    return not freq
TimeO(n+m)
SpaceO(n+m)
Open on LeetCode
00:00
3 local tests readyRun with ⌘/Ctrl + Enter. Your code stays in this browser.

Runs solve(...) locally in a browser worker. SWE Playbook does not submit your code. Only run code you trust; Python code may access the network.