Five interview problems that build with stacks and queues: queues from stacks, a ring of pings, bracket runs, a calculator and a max stack. The move: say what each entry means and what removes it.
You write code for a photo app, a map app and a fee service. The five problems on this street come from them. Each uses a stack or a queue for more than storing items.
Here is what each entry means, and what removes it.
| Problem | An entry means | What removes it |
|---|---|---|
| Photo uploads from two stacks | an upload waiting its turn | the output stack gives it up |
| A ring of the latest pings | a ping at a ring position | the head moves past it |
| Longest well-formed stretch | the position of an open bracket, or the last position that cannot be used | a close bracket |
| Fee formula with brackets | the total and the sign before a group | the close bracket of that group |
| Take the best offer from a stack | an offer and the largest offer below it | pop or popmax |
When you can fill both columns in one sentence each, the code is short. When you cannot, you are guessing at the structure.
Exercise · Predict the output: The fee with a bracket. The code keeps a running total and a sign. An open bracket pushes both and starts again. What does it print?
expr = "10-(4+(3-1))"
result = 0
sign = 1
number = 0
stack = []
for ch in expr + "+":
if "0" <= ch <= "9":
number = number * 10 + int(ch)
elif ch == "+" or ch == "-":
result += sign * number
number = 0
sign = 1 if ch == "+" else -1
elif ch == "(":
stack.append(result)
stack.append(sign)
result = 0
sign = 1
else:
result += sign * number
number = 0
result = stack.pop() * result + stack.pop()
print(result)Before you write any code, answer two questions in one sentence each. What does an entry in the structure mean, and which event removes it?
Every entry stands for something still open: a bracket, a total, a waiting upload. It stays until the one event that closes it, and then it leaves, so the top is always the newest thing still open.
The answers tell you the updates.
Try the two sentences on the max stack. An entry is an offer together with the largest offer at or below it in the stack. A pop removes the top entry, while top and peekmax only read.
The command popmax removes the largest offer nearest the top, so it must dig through the entries above it and put them back. That needs a second stack to hold them, and the two sentences already told you that one structure would not be enough.
A bracket pushes the total and sign; the matching close folds the group's value back in with that sign.
Exercise · Find the bug: The first run goes missing. This returns the length of the longest well-formed run of brackets. It crashes on some inputs and returns 0 on others. Which line is wrong?
def longest_run(trace):
stack = []
best = 0
for i, c in enumerate(trace):
if c == "(":
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
else:
best = max(best, i - stack[-1])
return bestThe Academy lessons Stacks, Parsing and expression evaluation and Queues and deques teach each structure on its own. This street changes three things.
You build one structure from another. Two stacks give a queue, but only if you move items across at the right moment. For 100,000 uploads followed by 100,000 reads, each item moves once. Moving on every read would put new uploads on top of old ones.
The structure has a base entry. A stack that starts with -1 turns the first run into an ordinary case. On )()()) the stack is [0] after the close brackets at positions 2 and 4, so the longest run is 4 minus 0, which is 4.
The ring has two numbers. A ring of capacity 5 keeps a head index and a size, and the next free cell is (head + size) % capacity. After three adds and two drops, the head is 2 and the next three adds land on cells 3, 4 and 0, so the ring wraps.
Refilling the output stack on every read puts new uploads above old ones: refill only when it is empty.
Exercise · Break it: The queue that refills too often. This is a queue made of two stacks. A positive number is an upload and 0 is a read, which answers the oldest upload or -1 when the queue is empty. Find an input where it answers wrongly.
def queue_reads(ops):
inbox, outbox, answers = [], [], []
for op in ops:
if op > 0:
inbox.append(op)
else:
while inbox:
outbox.append(inbox.pop())
answers.append(outbox.pop() if outbox else -1)
return answersSolve them in this order. The queue and the ring build one structure from simpler parts. The bracket run, the calculator and the max stack give a stack a job.
Before you code each problem, write the two sentences: what an entry means and what removes it. If the second sentence has two answers, the problem needs two structures, as the max stack does.
Give each problem about 25 minutes. Spend the first five on the two sentences and one short example, with the stack drawn after every step.
Test the empty case, a single entry, and an input that ends with entries still open. Most wrong answers on this street come from a missing base entry or from an entry that leaves at the wrong event.
Checkpoint · Stacks and queues at work
Q1/5 You build a queue from two stacks. When do you move items from the input stack to the output stack?
Answer: B
The output stack holds the oldest items on top. Refilling it while it still holds items puts newer items above older ones.
Q2/5 The longest valid run of brackets uses a stack that starts with -1. What does that entry stand for?
Answer: B
It marks the position before the string, so a run that starts at index 0 is measured like any other run: i minus the top.
Q3/5 A formula calculator meets an open bracket. What does it push?
Answer: B
The total and sign before the group are needed again when the close bracket folds the group in, so both go on the stack.
Q4/5 What does the formula 10-(4+(3-1)) evaluate to with a total and sign stack?
Answer: B
3 - 1 is 2, the group 4 + 2 is 6, and 10 minus 6 is 4. Ignoring the minus before the group would give 16.
Q5/5 A ring of capacity 5 has head 2 and size 1. Which cell does the next add use?
Answer: B
The next free cell is (head + size) % capacity, which is (2 + 1) % 5 = 3.
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.