InterviewPrepKit

Home / Coding / Arrays & Hashing

Valid Anagram

easy Original ↗
Solving tips
  • When 'rearrangement doesn't matter,' compare frequency signatures, not sequences.
  • Tally 26 letter counts (increment for s, decrement for t in one combined pass) and require all counters to be zero; O(n) time, O(1) space.
  • Sorting both strings and comparing works too (O(n log n)) but the interviewer usually wants the O(n) counting argument; for the Unicode follow-up swap the fixed array for Counter.
  • Pitfall: check len(s)==len(t) first when using zip (it truncates to the shorter string), and never compare set(s)==set(t), which drops multiplicity.

Problem

Given two strings s and t, return True if t is an anagram of s — that is, if t can be formed by rearranging the letters of s, using every letter exactly once — and False otherwise.

Examples

  • s = "anagram", t = "nagaram"True — same letters, same multiplicities (3×a, 1 each of n, g, r, m).
  • s = "rat", t = "car"Falset contains a c that s doesn’t have.
  • s = "ab", t = "abb"False — different lengths can never be anagrams.

Constraints

  • 1 <= s.length, t.length <= 5 * 10^4
  • s and t consist of lowercase English letters.

Follow-up: what would you change if the inputs could contain any Unicode characters?

Think about it first

Hint 1 Two strings are anagrams exactly when some canonical form of each is identical. What canonical form ignores letter order?
Hint 2 Sorting works but costs O(n log n). Order doesn't actually matter — only how many times each letter appears. Can you compare that directly?
Hint 3 Count the 26 letter frequencies of each string (an array of 26 ints, or a `Counter`) and compare the two tallies — one pass over each string.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.