Skip to content
DSA Patterns
Menu
Language
HashingLC #2425 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Valid Anagram

Problem (restated)

Return true if t is an anagram of s (same characters with same frequencies).

Intuition

Anagrams share a multiset of characters. Compare frequency maps or sorted forms.

Approaches

Character counts

Unverified
Time O(n)Space O(1)

Idea. Count letters in s, decrement with t; all zeros means anagram. Assumes lowercase English.

Walkthrough. “anagram” / “nagaram” → counts cancel → true.

Trade-offs. Sorting is simpler but O(n log n). Unicode needs a hash map.

Solution
export function isAnagram(s: string, t: string): boolean {
  if (s.length !== t.length) return false;
  const cnt = new Array<number>(26).fill(0);
  for (let i = 0; i < s.length; i++) {
    cnt[s.charCodeAt(i)! - 97]!++;
    cnt[t.charCodeAt(i)! - 97]!--;
  }
  return cnt.every((c) => c === 0);
}
export function isAnagram(s: string, t: string): boolean {
  if (s.length !== t.length) return false;
  const cnt = new Array<number>(26).fill(0);
  for (let i = 0; i < s.length; i++) {
    cnt[s.charCodeAt(i)! - 97]!++;
    cnt[t.charCodeAt(i)! - 97]!--;
  }
  return cnt.every((c) => c === 0);
}

Template connection

Count the 26 letters of each string, or sort both and compare. The counts must match. Different lengths answer false before any count. The same letters in a different order are an anagram.

Reflection

  • Equal frequencies are a count array or a map. When is sorting both strings enough?
  • Rejecting different lengths up front makes which inputs O(1)?
  • This problem has no case folding. Did you still check that s and t have the same length?
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Valid anagram: same multiset of letters. Count s, then spend t.

a
0
n
1
a
2
g
3
r
4
a
5
m
6

t = nagaram

Key:CurrentActive rangeMatchSettled