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 - Single Pass Counter Array INPUT String s = "anagram" a n a g r a m String t = "nagaram" n a g a r a m Counter Array (26 chars) [0, 0, 0, ... 0] (all zeros) Length check: s.length == t.length == 7 s = "anagram" t = "nagaram" ALGORITHM STEPS 1 Create counter[26] Array for a-z chars 2 Single pass loop Iterate both strings 3 Update counters s[i]: +1, t[i]: -1 Counter after processing: a: +3-3=0 g: +1-1=0 m: +1-1=0 n: +1-1=0 r: +1-1=0 All = 0 4 Check all zeros If all 0: anagram! Time: O(n) Space: O(1) - fixed 26 chars FINAL RESULT All counter values = 0 a 0 g 0 m 0 n 0 r 0 Output: true "anagram" and "nagaram" are valid anagrams! Letter count match: a:3, n:1, g:1, r:1, m:1 [OK] Same in both strings Key Insight: Use a single counter array to track character frequency differences. Increment for string s, decrement for string t. If all counters are zero after processing, the strings are anagrams. TutorialsPoint - Valid Anagram | Single Pass Counter Array Approach
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