Valid Anagram
Valid Anagram is LeetCode 242 (Easy). Given two strings s and t, return true if t uses exactly the same letters as s, each the same number of times, only in a different order. Otherwise return false.
- Both strings hold only lowercase English letters, so there are just 26 possible characters.
- Each string can be 50,000 characters long, so comparing every arrangement is out of the question; one pass per string is the target.
- 1 <= s.length, t.length <= 5 * 10^4
- s and t consist of lowercase English letters.
Intuition
Order does not matter, only how many times each letter appears. So keep one counter per letter: add 1 for every letter of s, then take 1 away for every letter of t.
If the strings have the same length, it is enough to watch for a counter that drops below zero. A negative counter means t used some letter more often than s has it. If that never happens, every counter ends at exactly zero, because the additions and subtractions were the same in number and none of them overshot. Zero everywhere means the letter counts match.
Any question of the form "same items, order ignored" is a frequency count. Group Anagrams turns the counts into a key to bucket many words, and Find All Anagrams in a String slides the same counts along a longer string.
Approach
Before reading on, decide what a 26-slot array should hold after reading s, and when reading t can stop early. Aim for O(n) time and O(1) extra space.
Two ways to solve it
Add for s, subtract for t, stop at the first negative slot.
- Linear: one look at each character.
- Early exit: a mismatch often shows up before
tis finished.
Two strings are anagrams exactly when their sorted forms are equal.
- Shortest code: one line in Python.
- Works for any alphabet without changing anything.
Both give the right answer. Counting is faster and is what the steps, code and live demo follow; sorting comes after the demo.
Reject different lengths
If len(s) != len(t) return false straight away. Strings of different lengths can never have equal letter counts.
Tally the letters of s
Make an array of 26 zeros and add 1 at position ch - 'a' for every letter of s. After this pass each slot holds how many copies of that letter t is allowed to use.
Spend the tally with t
For every letter of t, subtract 1 from its slot. If the slot goes below zero, return false: t has asked for one more copy of that letter than s owns.
Finish with true
If t ends without any slot going negative, return true. The total added equals the total subtracted, and no slot went below zero, so no slot can be left above zero either.
Code in Python, C++ and Java
Sort both strings
Sorting puts equal letters next to each other, so two anagrams sort into the same string: listen and silent both become eilnst. Compare the sorted copies and you are done. Strings are immutable in Python and Java, so the sort makes copies, which is where the O(n) space comes from.
Common pitfalls
Checking which letters appear, not how often
return set(s) == set(t)
count every letter, or compare Counter(s) == Counter(t)
A set forgets repeats. s = "aab" and t = "abb" have the same set {a, b} but are not anagrams: s has two a's and t has one.
Dropping the length check before the early exit
for ch in t: ... if count < 0: return False return True
if len(s) != len(t): return False first
Without it, s = "ab" and t = "a" return true: t never pushes a slot below zero, yet the b slot is left at 1. The zero-sum argument needs equal lengths.
Complexity
Valid Anagram FAQ
How would this change if the strings could contain any Unicode character?
A fixed 26-slot array no longer fits, so count with a hash map keyed by character (Counter in Python, HashMap<Integer, Integer> over code points in Java). Count code points rather than UTF-16 units, or an emoji made of two units will be split.
Is sorting both strings an acceptable answer in an interview?
It is correct and quick to write, so it is a fine first answer. Expect the follow-up to bring it down from O(n log n) to O(n), which is what the counting array does.