AlgoViz
← All problems

Valid Anagram

Easy+60 XPteaches: Hashing (Hash Set)

Given two strings `s` and `t`, return `true` if `t` is an anagram of `s` — that is, `t` uses exactly the same letters as `s`, the same number of times, just reordered. Otherwise return `false`.

Example: s = "anagram", t = "nagaram" → true

Sort & compare: Sort both strings; they're anagrams iff the sorted forms are equal. (time O(n log n), space O(n))

No visualization loaded.

Watch

i

Press Run to begin.

Why the best approach wins

Sorting both strings works but costs O(n log n). Counting letters is O(n): walk s adding to a tally and t subtracting, then check every tally is zero. With a fixed alphabet the count table is constant size, so space is O(1).

Sort & compare: O(n log n) time / O(n) spaceLetter counts: O(n) time / O(1) space

Your turn — implement isAnagram

Loading editor…