Valid Anagram - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

To determine whether s and t are anagrams, we compare their character multisets using a single frequency map:

  • Early exit by length: If s.length !== t.length, they cannot be anagrams β†’ return false.
  • Build counts from s: Create a hashmap charCounts. For each character ch in s, increment charCounts[ch].
  • Consume with t: Iterate characters of t:
    • If ch is not in charCounts, then t contains more of ch than s β†’ not an anagram β†’ return false.
    • Otherwise, decrement charCounts[ch]. If it becomes zero, remove the entry.
  • Final check: After consuming all of t, if charCounts is empty, then s and t contain exactly the same multiset of characters β†’ return true. Otherwise, return false.

Why this works: By incrementing counts for every character in s and then decrementing for each character in t, the algorithm checks whether the two strings perfectly balance each other’s character frequencies. If a deficit occurs during processing (a missing or overused character) or if any counts remain afterward (charCounts map is not empty), the balance is broken β€” meaning the strings differ in frequency. If processing completes with no deficits and the charCounts map is empty, it confirms that s and t contain exactly the same multiset of characters, proving they are true anagrams.

Time Complexity

Let n = s.length = t.length. (If their lengths differ, the function exits immediately in O(1) time.)

When lengths are equal, the algorithm runs in O(n) time:

  • Build counts from s: One pass over s β†’ O(n).
  • Consume with t: One pass over t β†’ O(n).

Each step performs only constant-time hashmap operations per character, so the total runtime is O(n).

Space Complexity

The frequency map charCounts stores at most one entry per distinct character in s. Since both strings consist of lowercase English letters, there are at most 26 possible keys. Therefore, the auxiliary space is effectively O(1) β€” constant with respect to input length.

Visucodize editorial solution titled JS Solution for LeetCode's Valid Anagram coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/valid-anagram.