Six classic interview problems on stacks, a prefix index, intervals, jumps and bit counts, in our own wording. Spot the signal, pick the small structure, and test the edge.
Many coding-round classics need nothing larger than a stack, a few arrays or a tree of letters. They are asked because the structure is small and the mistake is easy to make. The story talks about hours of latency, a cart with an Undo button, or a search box that suggests words.
This set collects six classics that the launch districts do not cover yet. Each one is our own version of a well-known interview problem, so you can practise the classics without memorising someone else's wording.
Interviewers stress three things with these problems.
The stack for waiting hours is the one to trace by hand. Each hour waits until a later hour is slower, and the stack holds the waiting hours.
Exercise · Predict the output: Who waits for a slower hour?. Each hour waits for the first later hour with a larger latency. The stack holds waiting hours, and a new hour pops every smaller one. What does this print?
latencies = [3, 1, 2, 5, 2]
answers = [0] * len(latencies)
stack = []
for hour, value in enumerate(latencies):
while stack and latencies[stack[-1]] < value:
waiting = stack.pop()
answers[waiting] = hour - waiting
stack.append(hour)
print(*answers)Each problem gives itself away with a signal in the statement. Here are the signals of the six problems, with the move and the Academy lesson that teaches it.
| Signal in the statement | The move | Academy lesson |
|---|---|---|
| the next larger value to the right | monotonic stack of waiting items | Monotonic stack |
| the minimum after every step, with undo | a stack that stores the minimum so far | Stacks |
| words that share a start, prefix questions | a trie with an end mark | Tries |
| the fewest points to hit every interval | sort by end, pin the end of the first unhit one | Greedy by sorting |
| can a rider reach the last stop | one number, the farthest reach | Greedy choices |
| a bit count for every number up to n | each count comes from the number halved | Bits and maths |
The Academy lessons teach each structure on its own. This set mixes them, so the skill you practise is choosing. Read the statement, find the signal, and name the structure before you write a line.
A stack can carry more than the items. For a cart with an Undo button, each entry also stores the cheapest price from the bottom up to that item. Then every add and every undo answers in one step, because the top entry is always the answer.
A monotonic stack holds the hours still waiting for a slower one; a new hour pops every smaller waiting hour and tells how long it waited.
Exercise · Find the bug: The entry that forgets the minimum. A positive number adds an item with that price, and 0 presses Undo. After each action this returns the cheapest price in the cart, or -1 when it is empty. Each stack entry should hold the cheapest price up to that item. Which line is wrong?
def cheapest_after_each(actions):
stack = []
answers = []
for action in actions:
if action == 0:
if stack:
stack.pop()
else:
stack.append(action)
answers.append(stack[-1] if stack else -1)
return answersA reach test needs the same care with one comparison. A rider can stand on stop i only if i is not beyond the farthest stop reached so far. So the test is "more than", and a test of "at least" fails at the first stop.
Exercise · Put it in order: The farthest reach. Arrange the lines into a function that says whether a rider starting at stop 0 can reach the last stop. hops[i] is the most stops ahead that the shuttle at stop i can go.
def can_reach(hops):
farthest = 0
for i in range(len(hops)):
if i > farthest:
return False
farthest = max(farthest, i + hops[i])
return True
if i >= farthest:The first two are easy and each keeps one number or one array. The next four are medium, and each adds a structure: a stack with a minimum, a monotonic stack, a sort by end and a trie. The minutes are time boxes for practice, close to what an interview allows.
Three of the twists are worth knowing before you start. The bit counts need no loop over bits, because the count of a number is the count of half of it plus its last bit. The intervals must be sorted by their end, not their start. And the trie must mark the end of a word, or a search for a word cannot tell it from a start of one.
The sort order is where the interval problem is usually lost. Taking the end of the first show by start time can leave a later, shorter show unreached.
To hit every show with the fewest notifications, sort the shows by end and send at the end of the first unreached one.
Exercise · Break it: The shows sorted by the wrong end. A notification at second t reaches every show with start <= t <= end. This sorts the shows by start, sends one at the end of the first unreached show, and counts them. Find an input where it is wrong.
def fewest_pings(shows):
ordered = sorted(shows)
count = 0
last = None
for start, end in ordered:
if last is None or start > last:
count += 1
last = end
return countIn an interview, say the invariant out loud: "the stack holds the waiting hours, and their values never rise from bottom to top". It shows the interviewer your thinking, and it catches a wrong comparison early.
The six time boxes add up to 130 minutes. Split them into two sittings: the two easy problems and the stack with a minimum take 50 minutes, and the other three take 80.
If you finish a problem early, use the rest of its box well. Explain the structure aloud in one minute, as you would at the end of an interview, and say its cost in time and memory.
Checkpoint · Stacks, tries and more
Q1/5 Latencies for five hours are 3, 1, 2, 5 and 2. How many hours does hour 0 wait for a larger value?
Answer: C
Hour 0 has latency 3. The first later hour with a larger latency is hour 3, which has 5, so it waits 3 hours.
Q2/5 A cart gets items priced 3 and then 5. What should the cheapest price be after both, and what does a stack of raw prices say?
Answer: B
Each entry must hold the cheapest price up to that item. A raw price makes the top entry the newest price, which is 5.
Q3/5 After inserting card into a trie, why must search for car answer no, while a prefix query for car answers yes?
Answer: B
A node exists whenever it is a prefix of a stored word. Only the end mark says that the prefix was stored as a whole word.
Q4/5 Shows run from 1 to 10, from 2 to 3 and from 5 to 6. What is the fewest number of notifications that reach every show?
Answer: B
Notifications at second 3 and at second 6 reach all three shows. Sorting by start would send one at second 10 and miss the other two.
Q5/5 Which rule gives the number of 1 bits of i from an earlier entry of the list?
Answer: B
The binary form of i is the binary form of i halved with the last bit added, so its count is the count of the half plus that last bit.
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.