TRT
Sign in
easyCoreLeetCode#counting#frequency array

Valid anagram

Decide whether two strings are anagrams by counting letters instead of sorting, in O(n) time.

The Runtime Theory Team1 min read
Taught inCounting and radix sortPro — members onlyNo sort that only compares elements can beat about n log n comparisons. Counting sort and radix sort don't compare at all: they use the keys as numbers, and sort integers in linear time.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

ins = "anagram", t = "nagaram"

outtrue

ins = "rat", t = "car"

outfalse

ins = "a", t = "ab"

outfalse

Given two strings, return whether one is an anagram of the other: the same letters with the same counts, in any order. The strings contain lowercase English letters.

Before you code

Sorting both strings and comparing works in O(n log n). Two strings are anagrams exactly when their letter counts match, and counting is the first pass of counting sort: O(n) with 26 counters.

Hints

  1. If the lengths differ, return false immediately.
  2. Use an array of 26 counts: add 1 for each letter of s and subtract 1 for each letter of t.
  3. The strings are anagrams if every count ends at 0.
  4. Follow-up: for arbitrary Unicode text, use a hash map of counts instead of a fixed array.

Production & complexity notes

When solving Valid anagram on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Counting and radix sort to reinforce the underlying pattern.

What it practices

Using the values themselves instead of comparisons, from Counting and radix sort.

Not started

Sign in to save your learning progress.

Sign in to save