Valid Anagram - Problem

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

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.

Input & Output

Example 1 — Basic Anagram
$ Input: s = "anagram", t = "nagaram"
Output: true
💡 Note: Both strings contain exactly the same characters with the same frequencies: a(3), g(1), m(1), n(1), r(1). The letters are just rearranged.
Example 2 — Not an Anagram
$ Input: s = "rat", t = "car"
Output: false
💡 Note: The strings have different characters: 'rat' has 't' but 'car' has 'c'. They cannot be anagrams of each other.
Example 3 — Different Lengths
$ Input: s = "listen", t = "silent"
Output: true
💡 Note: Both strings have the same length and characters: e(1), i(1), l(1), n(1), s(1), t(1). They are perfect anagrams.

Constraints

  • 1 ≤ s.length, t.length ≤ 5 × 104
  • s and t consist of lowercase English letters

Visualization

Tap to expand
Valid Anagram Problem OverviewInput Strings:s = "anagram"t = "nagaram"Character Analysis:Both contain:• a: 3 times• g, m, n, r: 1 time each• Same length: 7Since character frequencies match exactly:Result: true✅ These strings are valid anagrams
Understanding the Visualization
1
Input
Two strings s and t to compare
2
Process
Count character frequencies or sort characters
3
Output
Return true if anagrams, false otherwise
Key Takeaway
🎯 Key Insight: Anagrams have identical character frequencies - count and compare to determine validity
Asked in
Amazon 45 Facebook 38 Bloomberg 32 Microsoft 28
321.3K Views
High Frequency
~15 min Avg. Time
8.5K 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