05. Check if Two Strings are Anagrams

Difficulty:EasyPattern:Frequency MapTime:O(n)Space:O(1)

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

How It Works & Algorithmic Design

An anagram contains the exact same characters with the exact same frequencies, reordered.

  1. Length Pre-Check: If s.length !== t.length, they cannot be anagrams. Return false immediately.
  2. Frequency Map: Traverse string s and record character counts in a Hash Map (or a fixed 26-element array for lowercase English letters).
  3. Frequency Verification: Traverse string t. For each character, check if it exists in the map with a count $> 0$. Decrement its count in the map. If a character is missing or its count reaches negative, return false.
  4. Completion: If all characters in t match and exhaust the counts in s, return true.

Why This Approach Works Best

Sorting both strings takes $O(n \log n)$ time. Using a frequency map checks anagrams in $O(n)$ time complexity and $O(k)$ space (where $k$ is the alphabet size, $O(1)$ for fixed character sets).

Example Walkthrough 1

Input

s = "listen", t = "silent"

Same letters, different order.

Execution Trace

s map: {l:1, i:1, s:1, t:1, e:1, n:1} -> t matches every key count exactly.

Frequency counts balance out to zero.

Output

true

Valid anagram pair.

Answer: Anagram verification using frequency map

function isAnagram(s, t) {
  if (s.length !== t.length) return false;
  const count = {};
  for (const ch of s) count[ch] = (count[ch] || 0) + 1;
  for (const ch of t) {
    if (!count[ch]) return false;
    count[ch]--;
  }
  return true;
}

Count character occurrences in the first string and verify them against the second string.

Key Takeaways
  • Always check string lengths first for instant early termination.

  • Frequency map eliminates the need for $O(n \log n)$ sorting operations.

  • For lowercase ASCII strings, a fixed 26-element array can replace a dynamic hash table for better performance.