DSA Visualizer · 25 visualizationsValid Anagram
EasyArrays & Hashing
Valid Anagram
Given two strings s and t, return true if t is an anagram of s.
s = "aab" · t = "baa"Step 1 of 8
a
0a
1b
2count
emptyBoth strings have 3 letters, so an anagram is still possible. Now count the letters of s.
Pythontime O(n) · space O(1)
1def isAnagram(s, t):
2 if len(s) != len(t):
3 return False
4 count = {}
5 for c in s:
6 count[c] = count.get(c, 0) + 1
7 for c in t:
8 if count.get(c, 0) == 0:
9 return False
10 count[c] -= 1
11 return True
Variables
saab
tbaa
c—
count—
Problem
Given two strings s and t, return true if t is an anagram of s.
An anagram uses all original letters exactly once. Approach: Count character frequencies in s, then decrement for each character in t. If any count goes negative or lengths differ → false.
Examples
Input: s = "anagram", t = "nagaram"Output: true
Input: s = "rat", t = "car"Output: false
Constraints
- 1 ≤ s.length, t.length ≤ 5×10⁴
- s and t consist of lowercase English letters
Intuition
Two words are anagrams exactly when they use the same multiset of letters. So count the letters of one word and cancel them against the other.
Brute force → Optimal
Brute force
Sort both strings and compare them character by character.
Time O(n log n)Space O(n)
Optimal
Count each letter of s in a map, then subtract each letter of t; a letter that is missing or over-used fails the check.
Time O(n)Space O(1)
Complexity
Time O(n)Space O(1)
Edge cases
- Different lengths fail immediately, without counting any letters.
- A letter that appears in t but never in s (e.g. "rat" vs "car") hits a zero count early.
- Repeated letters, e.g. "aab" vs "aba", must match in quantity, not just presence.
Common mistakes
- Comparing only the set of characters and ignoring how many times each appears.
- Skipping the length check, then missing a leftover letter at the end.
Climbing StairsPrevious
Next upMerge Two Sorted Lists
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free