Valid Anagram - Problem
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, "listen" and "silent" are anagrams of each other.
Given two strings s and t, determine if t is an anagram of s. Return true if they are anagrams, false otherwise.
Note: You may assume the strings contain only lowercase English letters.
Input & Output
example_1.py โ Basic Anagram
$
Input:
s = "anagram", t = "nagaram"
โบ
Output:
true
๐ก Note:
Both strings contain exactly the same characters with the same frequencies: a(3), n(1), g(1), r(1), m(1). Rearranging 'anagram' gives 'nagaram'.
example_2.py โ Not Anagram
$
Input:
s = "rat", t = "car"
โบ
Output:
false
๐ก Note:
The strings have different characters. 'rat' contains 'r', 'a', 't' while 'car' contains 'c', 'a', 'r'. They don't have the same character frequencies.
example_3.py โ Different Lengths
$
Input:
s = "a", t = "ab"
โบ
Output:
false
๐ก Note:
Strings of different lengths cannot be anagrams since they don't contain the same number of characters.
Constraints
- 1 โค s.length, t.length โค 5 ร 104
- s and t consist of lowercase English letters only
- Follow-up: What if the inputs contain Unicode characters?
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Balance
Start with empty hash table (balanced scale)
2
Process Characters
For each position i: add s[i] weight (+1), remove t[i] weight (-1)
3
Check Final Balance
If all character counts are zero, the strings are anagrams
Key Takeaway
๐ฏ Key Insight: Two strings are anagrams if and only if they have identical character frequency distributions. The one-pass hash table approach elegantly solves this by maintaining a running balance of character counts.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code