LeetCode #242 Easy

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.
Constraints
  • 1 <= s.length, t.length <= 5 * 10^4
  • s and t consist of lowercase English letters.
stringhash-tablecounting
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

Reject different lengths

If len(s) != len(t) return false straight away. Strings of different lengths can never have equal letter counts.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def isAnagram(self, s: str, t: str) -> bool:
▶3 if len(s) != len(t):
▶4 return False
▶5 count = [0] * 26
▶6 for ch in s:
▶7 count[ord(ch) - ord("a")] += 1
▶8 for ch in t:
▶9 i = ord(ch) - ord("a")
▶10 count[i] -= 1
▶11 if count[i] < 0:
▶12 return False
▶13 return True
sanagramtnagaramcounta1g0m0n0r0s has 'a' → its count goes up to 1
letter'a'
count1
Both strings have 7 letters, so counting can start. Each letter of s adds one to its counter: the counters will say how many copies of each letter t may use.
sanagramtnagaramcounta1g0m0n1r0s has 'n' → its count goes up to 1
letter'n'
count1
Another 'n' in s, so t may use one more of them.
sanagramtnagaramcounta2g0m0n1r0s has 'a' → its count goes up to 2
letter'a'
count2
Another 'a' in s, so t may use one more of them.
sanagramtnagaramcounta2g1m0n1r0s has 'g' → its count goes up to 1
letter'g'
count1
Another 'g' in s, so t may use one more of them.
sanagramtnagaramcounta2g1m0n1r1s has 'r' → its count goes up to 1
letter'r'
count1
Another 'r' in s, so t may use one more of them.
sanagramtnagaramcounta3g1m0n1r1s has 'a' → its count goes up to 3
letter'a'
count3
Another 'a' in s, so t may use one more of them.
sanagramtnagaramcounta3g1m1n1r1s has 'm' → its count goes up to 1
letter'm'
count1
Another 'm' in s, so t may use one more of them.
sanagramtnagaramcounta3g1m1n0r1t uses one 'n' → 0 left to spend
letter'n'
count0
Now t spends the counters. Each letter of t takes one away from its counter; the only thing to watch for is a counter going below zero.
sanagramtnagaramcounta2g1m1n0r1t uses one 'a' → 2 left to spend
letter'a'
count2
'a' is still available in s, so the counter stays at zero or above and the check moves on.
sanagramtnagaramcounta2g0m1n0r1t uses one 'g' → 0 left to spend
letter'g'
count0
'g' is still available in s, so the counter stays at zero or above and the check moves on.
sanagramtnagaramcounta1g0m1n0r1t uses one 'a' → 1 left to spend
letter'a'
count1
'a' is still available in s, so the counter stays at zero or above and the check moves on.
sanagramtnagaramcounta1g0m1n0r0t uses one 'r' → 0 left to spend
letter'r'
count0
'r' is still available in s, so the counter stays at zero or above and the check moves on.
sanagramtnagaramcounta0g0m1n0r0t uses one 'a' → 0 left to spend
letter'a'
count0
'a' is still available in s, so the counter stays at zero or above and the check moves on.
sanagramtnagaramcounta0g0m0n0r0t uses one 'm' → 0 left to spend
letter'm'
count0
'm' is still available in s, so the counter stays at zero or above and the check moves on.
sanagramtnagaramcounta0g0m0n0r0no counter went below zero → anagram, true
resulttrue
t used 7 letters and s supplied 7, and no counter ever went negative. Equal totals with no overdraft means every counter is back at zero, so the letter counts match.
05

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.

▶1class Solution:
▶2 def isAnagram(self, s: str, t: str) -> bool:
▶3 return sorted(s) == sorted(t)
06

Common pitfalls

Checking which letters appear, not how often

✗ Wrong
return set(s) == set(t)
✓ Right
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

✗ Wrong
for ch in t: ... if count < 0: return False
return True
✓ Right
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.

07

Complexity

Time
O(n)
Space
O(1)
Each string is read once and each step is an array update. The array always has 26 slots whatever the input size, so the extra space is constant. Sorting instead costs O(n log n) time.
08

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.