Index

Free, with Google

Keep going, free.

A free account opens lessons 2 and 3 of every track, 33 more lessons, and keeps your progress and review cards on every device.

Start free with Google

A chalk plan

Open everything on chalk.

Every lesson, board, video, lab and paper, and the full review decks. Yearly is $39/year.

See plansStart free instead

Valid Anagram

EasyLeetCode 242 ↗

The problem, in one line. Given two strings, say whether the second is the first with its letters rearranged. LeetCode 242.

The tell. “Same letters, any order” means order does not matter and counts do. When order is thrown away, you compare tallies, not positions.

The wrong first idea

For each letter of the first word, search the second word for it and cross it out.

rest = list(t)
for ch in s:
    if ch in rest:
        rest.remove(ch)
    else:
        return False
return not rest

It works. Each letter triggers a search and a removal, so two words of 100,000 letters cost about 5 billion steps. The searching is the waste, because a tally of letters answers the same question in one pass.

The invariant

Keep one tally. Read both words side by side. A letter from the first word adds one, a letter from the second takes one away.

flowchart LR
  A["rat / car<br/>r: +1 -0 = 1"] --> B["a: +1 -1 = 0"]
  B --> C["t: +1 -0 = 1<br/>c: 0 -1 = -1"]
  C -->|"not all zero"| D["answer: False"]

The sentence that stays true every step: each tally equals the times that letter appeared in the first word minus the times it appeared in the second. The words are anagrams exactly when every tally ends at zero.

The solution

def is_anagram(s, t):
    if len(s) != len(t):
        return False
    count = {}
    for a, b in zip(s, t):
        count[a] = count.get(a, 0) + 1   # the first word adds a letter
        count[b] = count.get(b, 0) - 1   # the second word takes one back
    return all(v == 0 for v in count.values())

print(is_anagram("listen", "silent"))
print(is_anagram("rat", "car"))
print(is_anagram("aab", "abb"))
True
False
False
func isAnagram(s, t string) bool {
	if len(s) != len(t) {
		return false
	}
	count := map[rune]int{}
	ts := []rune(t)
	for i, a := range []rune(s) {
		count[a]++ // the first word adds a letter
		count[ts[i]]-- // the second word takes one back
	}
	for _, v := range count {
		if v != 0 {
			return false
		}
	}
	return true
}

Same three calls print true, false, false.

Complexity

  • Time O(n): one pass over both words, then one pass over the tally.
  • Space O(k): one entry per distinct letter, which is at most 26 for lowercase English.

Traps

  • Comparing the sets of letters. "aab" and "abb" have the same set and are not anagrams.
  • Skipping the length check. zip stops at the shorter word, so "ab" against "abc" would end with every tally at zero and wrongly say True.
  • Testing len(count) == 0 at the end. A tally that went up and back down stays in the map with value 0, so "ab" against "ba" would say False.

Next in the ladder

Two Sum turns the tally into a lookup of partners: you no longer count letters, you ask whether the number that completes this one is already behind you.