Five interview problems solved by dropping entries that can never matter again: colliding parcels, a smallest list, a 132 pattern, a shortest run and the best picks in a gap. The move: drop on arrival.
You work on a shipping belt, a filter service, a billing monitor and an ad planner. The five problems on this street come from them. Each one keeps a short list of candidates and removes the ones that cannot win any later contest.
Here is what each problem drops, and what triggers the drop.
| Problem | The dropped entry | What triggers the drop |
|---|---|---|
| Parcels colliding on a belt | a lighter right-moving parcel | a heavier left-moving parcel arrives |
| Smallest list that keeps every filter once | a larger filter already listed | a smaller filter arrives and the larger one appears again later |
| A spike that lands above where it started | a count below a newer, higher count | the higher count arrives from the right |
| Shortest run with a sum of at least k | a prefix sum no smaller than the new one, and a start that already reached the target | a new prefix sum arrives |
| Best picks within a gap | an earlier total no larger than the new one, or older than the gap | a new slot arrives |
The remaining entries are always in order, so the answer you want sits at the front or at the back.
In the parcels problem the dropped entries are real parcels that leave the belt. In the window problems they are only candidate starts, and dropping them changes no answer.
Exercise · Predict the output: How many parcels survive?. A positive number is a parcel moving right and a negative number is a parcel moving left. The heavier parcel survives a collision, and equal parcels destroy each other. What does the code print?
parcels = [4, -1, 5, -6, 2, 3, -2]
belt = []
for p in parcels:
alive = True
while alive and p < 0 and belt and belt[-1] > 0:
if belt[-1] < -p:
belt.pop()
elif belt[-1] == -p:
belt.pop()
alive = False
else:
alive = False
if alive:
belt.append(p)
print(len(belt))You decide who can still win before you write the loop. An entry that a newer entry beats for every later question is dropped at once, and the entries that remain stay in order.
When an item arrives, remove every entry it makes useless for all later questions. The entries that remain are in order, so each answer is at the front or at the back, and each item enters and leaves once.
Each problem fills in what useless means.
Each item enters once and leaves at most once, so the whole pass costs about two steps for each item. That holds even when one arrival removes many entries, because the earlier arrivals paid for those removals.
The edges need care. Equal prefix sums drop the older start, since a later equal start gives a shorter run. Equal parcels destroy each other, and a letter already in the list is skipped.
A heavier left-moving parcel pops every lighter right-moving parcel off the stack, and may be destroyed itself.
Exercise · Find the bug: One start at a time. This finds the shortest run of days whose changes add up to at least the target, or -1. The deque holds prefix-sum positions in increasing order of their sums. It sometimes reports a run that is too long. Which line is wrong?
def shortest_run(changes, target):
prefix = [0]
for c in changes:
prefix.append(prefix[-1] + c)
deque = []
best = -1
for i in range(len(prefix)):
if deque and prefix[i] - prefix[deque[0]] >= target:
length = i - deque.pop(0)
best = length if best == -1 else min(best, length)
while deque and prefix[deque[-1]] >= prefix[i]:
deque.pop()
deque.append(i)
return bestThe Academy lessons Stacks, Monotonic stacks and Monotonic deque teach the structure on a plain array. This street changes three things.
The order is hidden. The belt hides it in signs, since only a left-mover can destroy a right-mover. The smallest list hides it in the letters that still appear later.
For cbacdcbc the smallest list is acdb. A version that ignores the later copies returns abc, which drops the filter d.
The window is a prefix-sum window. With negative changes, a window cannot shrink from the left, since a longer run can have a larger sum. The deque keeps prefix-sum positions instead. For 100,000 days, it made 199,812 deque operations, and all pairs of starts and ends would be 4,999,950,000.
The front is dropped in a loop. One new prefix sum can retire several starts at once, as the bug above shows, so the front is dropped with while. The three stack problems differ in what useless means, and the two deque problems differ in what is measured at the front.
Pop a larger letter only if it appears again later, or the list loses a letter for good.
Exercise · Break it: The filter that vanishes. This builds the smallest list that keeps every letter of the text once, in the order of a subsequence. It pops a larger letter whenever a smaller one arrives. Find an input where the list loses a letter.
def smallest_list(text):
stack = []
for c in text:
if c in stack:
continue
while stack and stack[-1] > c:
stack.pop()
stack.append(c)
return "".join(stack)Solve them in this order. The first three use a stack, and the last two use a deque that also drops from the front.
Before you code each problem, finish this sentence: an entry is useless when. If you cannot, you do not yet know what the stack or deque should hold.
Give each problem about 25 minutes. Spend the first five on the sentence and one example, and write the structure after every item.
Test an input in strict order, an input in reverse order, and an input with equal values. Most wrong answers on this street come from a comparison that is strict where it should be loose, or the other way round.
Checkpoint · Next greater, spans and windows
Q1/5 A left-moving parcel of weight 6 meets a right-moving parcel of weight 4 on top of the stack. What happens?
Answer: A
The heavier parcel survives, so the 4 leaves the stack, and the 6 keeps going to meet the next parcel down, if there is one.
Q2/5 In the smallest list that keeps every filter once, when may a larger filter on the stack be popped?
Answer: B
If the larger filter has no later copy, popping it loses the filter for good. With a later copy, it can be added again in a better place.
Q3/5 For the text ba, what does a version that always pops a larger letter return?
Answer: B
The letter a arrives and pops the b, which never appears again. The result is a, and the list has lost the letter b.
Q4/5 Why is the front of a prefix-sum deque dropped with while and not if?
Answer: B
Several old starts can reach the target at the same new position, and each of them must be measured and dropped.
Q5/5 For 100,000 days a prefix-sum deque made 199,812 operations. What does that tell you?
Answer: A
There are 100,001 prefix sums, and each enters the deque once and leaves at most once. All pairs of starts and ends would be 4,999,950,000.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.