Arrays & Hashing · 051Easy
Valid Anagram
Given two strings s and t, return true if t is an anagram of s. An anagram uses exactly the same characters with the same counts, reordered.
Constraints
- 1 <= s.length, t.length <= 5 * 10^4
- s and t consist of lowercase English letters.
Examples
isAnagram("anagram", "nagaram") -> true
isAnagram("rat", "car") -> false
isAnagram("a", "ab") -> false // different lengths
isAnagram("a", "a") -> true // shortest possible input
isAnagram("ab", "ba") -> true // pure reordering
isAnagram("aacc", "ccac") -> false // same letter set, different countsEdge cases
- Character COUNTS must match, not just the set of characters.
- FOLLOW-UP
- Follow-up: what changes for Unicode input?
Show the target complexity (spoiler)
- Naive
- O(n log n) time — sort both strings and compare.
- Target
- O(n) time, O(1) space — a 26-slot count array incremented by s and decremented by t.
Solve it
By hand, in your editor. The runner checks answers and timing.
git clone https://github.com/sarmadkung/optimal-round cd optimal-round # open problems/01-arrays-hashing/051-valid-anagram.js ./practice c 051