The problem, in one line. Given a string of lowercase letters, keep deleting any two equal neighbours until none are left, then return what remains. LeetCode 1047.
The tell. Deleting a pair makes two new letters touch, and those might cancel too. When a removal can expose a fresh neighbour behind it, you want a stack, because the stack top is always the neighbour behind you.
The wrong first idea
Find a pair, delete it, and rescan from the start. Repeat until a full scan finds nothing.
changed = True
while changed:
changed = False
for i in range(len(s) - 1):
if s[i] == s[i + 1]:
s = s[:i] + s[i + 2:]
changed = True
break
It is correct. Each deletion costs a rescan and a rebuild of the string, so a nested string like abcddcba needs one round per pair, about n/2 rounds of n work. That is quadratic, and the stack removes the rescans.
The invariant
Walk the string once and keep a pile of survivors.
abbaca pile after each letter:
a -> a b -> ab b -> a (b cancels b)
a -> "" (a cancels a) c -> c a -> ca
The sentence that stays true every step: the pile is the answer for the part of the string read so far, with no two equal neighbours. The next letter only has to look at the top of the pile.
The solution
def remove_duplicates(s):
st = []
for c in s:
if st and st[-1] == c: # the newest survivor cancels with this letter
st.pop()
else:
st.append(c)
return "".join(st)
print(remove_duplicates("abbaca"))
print(remove_duplicates("azxxzy"))
print(remove_duplicates("aaaaa"))
ca
ay
a
func removeDuplicates(s string) string {
st := []byte{}
for i := 0; i < len(s); i++ {
if n := len(st); n > 0 && st[n-1] == s[i] { // the newest survivor cancels with this letter
st = st[:n-1]
} else {
st = append(st, s[i])
}
}
return string(st)
}
Same three calls print ca, ay, a.
Complexity
- Time O(n): one pass, and each letter is pushed once and popped at most once.
- Space O(n): the pile can hold the whole string when nothing cancels.
Traps
- Removing only one round of pairs. In
abbathe middlebbgoes, thenaabecomes adjacent and must go too. - Treating
aaaaaas all gone. Pairs cancel two at a time, so an odd run leaves one letter. - Comparing with the previous letter of the original string instead of the top of the pile. After
bbcancels inazxxzy, thezmust meet the earlierz, which the original string no longer shows as adjacent.
Next in the ladder
Min Stack keeps a stack too, but each entry now carries an extra fact about everything beneath it, so a question that sounds like it needs a scan is answered in one lookup.