Skip to content

Valid Anagram

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

An anagram is a word formed by rearranging all the letters of another word exactly once. Both strings must use the exact same characters with the exact same frequencies.

stOutputExplanation
"anagram""nagaram"trueSame letters, different order
"rat""car"falsec appears in t but not s
"a""ab"falseDifferent lengths
  • 1 <= s.length, t.length <= 5 * 10^4
  • s and t consist of lowercase English letters only.
ApproachTimeSpaceBest When
Hash MapO(n)O(1)*General case — single pass, fast
SortingO(n log n)O(n)Code simplicity matters more than speed

* At most 26 distinct lowercase letters, so the map size is bounded by a constant.

  • Pick Hash Map for interviews — O(n) with constant extra space is the expected answer.
  • Pick Sorting when you want the shortest possible implementation or are familiar with sort-based comparisons.
Best For Speed
Hash Map
O(n) time · O(1) space
Simplest Code
Sorting
O(n log n) time · O(n) space
★ Recommended

Count each character’s frequency in s with a hash map, then subtract for each character in t. If every count returns to zero, the strings are anagrams. An early-exit check on lengths avoids unnecessary work.

⏱ Time O(n) Two passes of length n 💾 Space O(1) At most 26 keys — constant

Input: s = "rat", t = "tar"

PhasecharMap state
Count sr{r:1}
Count sa{r:1, a:1}
Count st{r:1, a:1, t:1}
Subtract tt{r:1, a:1, t:0}
Subtract ta{r:1, a:0, t:0}
Subtract tr{r:0, a:0, t:0}
All zero?Yes → return true

Animated walkthrough

How frequency counting determines an anagram

Use Next or Autoplay to watch characters from s build up the count map, then characters from t subtract from it.

Step 1 of 4
Waiting to begin...
Array state
Memory / lookup state

function isAnagram(s, t):
if len(s) != len(t): return false
freq = {}
for char in s: freq[char] = freq.get(char, 0) + 1
for char in t:
freq[char] = freq.get(char, 0) - 1
if freq[char] < 0: return false
return true
valid_anagram_hash_map.py
from collections import Counter
def is_anagram(s: str, t: str) -> bool:
return Counter(s) == Counter(t)
✓ Simple

Sort both strings independently. If the sorted versions are equal, the original strings are anagrams — they contain the same characters in the same quantities, just in a different order.

⏱ Time O(n log n) Two sort passes 💾 Space O(n) Sorted char arrays

Input: s = "anagram", t = "nagaram"

StepValue
sorted(s)"aaagmnr"
sorted(t)"aaagmnr"
Equal?Yes → return true

Input: s = "rat", t = "car"

StepValue
sorted(s)"art"
sorted(t)"acr"
Equal?No → return false
function isAnagram(s, t):
return sorted(s) == sorted(t)
valid_anagram_sort.py
def is_anagram(s: str, t: str) -> bool:
return sorted(s) == sorted(t)
print(is_anagram("anagram", "nagaram")) # True
print(is_anagram("rat", "car")) # False
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
valid_anagram_space_optimized.py
"""
Solution for Valid Anagram
"""
def solve():
"""Implementation for approach 3 of Valid Anagram"""
pass
if __name__ == "__main__":
print("Solution ready")