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
Anagram Detection: The Scale Balance AnalogyString s"listen"Add weightsString t"silent"Remove weightsCharacter Balancel: +1-1 = 0 โœ“i: +1-1 = 0 โœ“s: +1-1 = 0 โœ“t: +1-1 = 0 โœ“e: +1-1 = 0 โœ“n: +1-1 = 0 โœ“Perfect Balance!๐Ÿ’ก Key Insight: Same characters with same frequencies will always balance out perfectlyDifferent characters or frequencies will leave the scale unbalanced (non-zero counts)Time: O(n) | Space: O(k) where k is the number of unique characters
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.
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28 Apple 22
125.6K Views
Very High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen