Typorithm · easy

Valid Anagram

valid-anagramarrays-hashingfrequency-countbalancenullish
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Valid Anagram

0%

Arrays & Hashing

Tally the first string's characters, decrement with the second; an empty tally means a match.

Anagrams use the exact same characters with the same frequencies.

Counting the first string then decrementing for the second drains the tally if they match.

Any missing character or leftover count means they are not anagrams.

01

Equal length is required.

02

Count up, then count down.

03

Empty tally means anagram.

function isAnagram(s, t) {
  if (s.length !== t.length) return false;

  const count = new Map();

  for (const ch of s) {
    count.set(ch, (count.get(ch) ?? 0) + 1);
  }

  for (const ch of t) {
    if (!count.has(ch)) return false;
    count.set(ch, count.get(ch) - 1);
    if (count.get(ch) === 0) count.delete(ch);
  }

  return count.size === 0;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Length gate

Different lengths can never be anagrams.

if (s.length !== t.length) return false

2. Tally first string

Count each character; ?? handles the first occurrence.

count.set(ch, (count.get(ch) ?? 0) + 1)

3. Extra character

A character not in the tally means t has an extra.

if (!count.has(ch)) return false

4. Remove at zero

Delete a character once its count balances to zero.

if (count.get(ch) === 0) count.delete(ch)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Valid Anagram: Lesson & Practice · Typorithm | ApplyDjinn