Eight interview problems about runs of a list and about everything except one item. The move: keep a running value, so any run is the difference of two stored values.
You work on a monitoring tool, a bank app, an ad platform, a warehouse system and a delivery app. The problems on this street come from all five. Each one asks about a run of neighbouring items, or about everything except one item.
What you need from a run changes from problem to problem. Here is each rule and what you keep while you scan.
| Problem | The question about a run | What you keep |
|---|---|---|
| Running median of three | the middle value of every three neighbours | an ordered pair of two readings |
| Product of the others | everything except position i | a prefix product and a suffix product |
| Where a shelf balances | the slot where two weighted sums are equal | the weight and the weight times the position, left of each slot |
| Longest run with equal zeros and ones | the same number of ones and zeros | the first index of each balance |
| Runs with a sum divisible by k | a total that is a multiple of k | the first index of each remainder |
| Loop runs that match a net load | a total equal to the budget, on a loop | counts of prefix sums in a sliding window |
| Smallest run reaching a target | a total of at least the target | prefix totals that never fall |
| Largest rectangle under a cap | a block with the biggest total under a limit | row-pair totals and a sorted set |
Read the last column. You never re-add a run. You store a running value once, and any run is a difference of two stored values.
The answers differ. Some are lengths, some are yes or no, and some are a whole list with one value for every position.
Decide what the running value is before you write code. For sums it is the total of the first i items. For products it is the product of the first i items, and a second one from the right.
After step i, you hold the running value of everything before position i. So the total of any run is a prefix total minus an earlier prefix total, and all-but-one is a prefix times a suffix.
Take the balance of a reaction list. A thumbs up scores +1 and a thumbs down scores -1. When two prefixes have the same balance, the reactions between them balance out. So the longest balanced run is the longest gap between two equal balances, and you keep only the first index of each balance.
Exercise · Predict the output: The longest balanced run. The code scores each 1 as +1 and each 0 as -1, and keeps the first index where each balance appeared. The map starts with balance 0 at index -1. What does it print?
bits = [1, 0, 0, 1, 1, 0, 1, 0, 0]
first = {0: -1}
balance = 0
best = 0
for i, b in enumerate(bits):
balance += 1 if b == 1 else -1
if balance in first:
best = max(best, i - first[balance])
else:
first[balance] = i
print(best)The map starts with balance 0 at index -1, before the list begins. That is the empty prefix, and a mistake here is easy to make.
Exercise · Find the bug: The empty prefix. This returns the length of the longest balanced run. It is right for most lists but wrong when the run starts at the first item. Which line is wrong?
def longest_balanced(bits):
first = {}
balance = 0
best = 0
for i, b in enumerate(bits):
balance += 1 if b == 1 else -1
if balance in first:
best = max(best, i - first[balance])
else:
first[balance] = i
return bestThe same idea works for products, but a product cannot be undone by division. When one value is zero, the total is zero and no division recovers the others. Instead, multiply what is to the left by what is to the right.
Exercise · Put it in order: Left times right. Arrange the lines into a function that returns, for every position, the product of all the other values. It must not divide.
def product_of_others(values):
n = len(values)
answer = [0] * n
left = 1
for i in range(n):
answer[i] = left
left *= values[i]
right = 1
for i in range(n - 1, -1, -1):
answer[i] *= right
right *= values[i]
return answer
answer[i] = left * values[i]Score each item plus or minus one and keep the first index of each balance. Equal balances mark a balanced run.
The Academy lessons Prefix sums in 1D and 2D and Prefix sum with a hash map build the running total and the map of totals. Difference arrays goes the other way. This street changes four things.
Not every running value has an inverse. A sum can be undone by subtraction. A product with a zero cannot be undone by division.
For the values 2, 0, 4 the answer is 0, 8, 0. Dividing the total 0 by each value gives 0, then an undefined 0 / 0, then 0, and the 8 is lost.
The first index is the right index. A longest run wants the widest gap, so store the first index of each key and never overwrite it. The key may be a balance or a remainder.
Remainders can be negative. In Java, C++ and JavaScript, -1 % 6 is -1, and in Python it is 5.
Make every remainder non-negative before it goes in the map, or equal classes look different.
A run needs a length. The task asks for two or more trips, so a single trip that is a multiple of k does not count. Check the gap i - first[key] >= 2, not only that the key was seen.
Exercise · Break it: A run of one trip. This checks whether two or more trips in a row have earnings that add up to a multiple of k. It keeps the first index of each remainder of the running sum. Find an input where it is wrong.
def has_even_run(amounts, k):
seen = {0: -1}
total = 0
for i, x in enumerate(amounts):
total = (total + x) % k
if total in seen:
return True
seen[total] = i
return FalsePrefix totals can be searched. When no load is negative, the prefix totals never fall, so one binary search finds the end of the shortest run. For 100,000 questions on 100,000 minutes, adding up each run costs up to 10,000,000,000 additions, and binary search costs about 1,700,000 steps.
Sums can pass 32 bits. One hundred thousand values of 1,000,000 total 100,000,000,000, which does not fit in a 32-bit int. Use 64 bits for every prefix total.
Two equal remainders at neighbouring indexes make a run of one. Check the gap is at least two.
Solve them in this order. The first is the smallest run, the next three keep a stored value for each position, and the last two search over stored totals.
Before you code each problem, write two lines: the running value you keep, and how a run or an all-but-one answer is built from two stored values. If you need a map, say which index it stores.
Give each problem about 20 minutes. Spend the first three on the two lines. Then walk a list of five items by hand, and write the stored values next to each item.
Three edge cases come back on most rungs. The empty prefix at index -1, a zero in a product, and a run that starts at the first item need a test each. Add a fourth for sums above two billion.
When a solution fails, check the empty prefix and the index you store. Most wrong answers on this street come from a missing seed, or from a map that keeps the latest index where the first one is needed.
Checkpoint · Prefix and product tricks
Q1/5 You keep prefix totals of a list. How do you get the total of the run from index a to index b?
Answer: B
A prefix total is the sum of everything before a position. The run total is the difference of two of them, so no run is added up twice.
Q2/5 The values are 2, 0, 4. Why can you not get the product of the others by dividing the total product by each value?
Answer: C
The correct answer is 0, 8, 0. The total product is 0, and dividing it by any value cannot give back the product of the other two. Use a prefix product and a suffix product.
Q3/5 You find the longest run whose balance is zero. Why does the map start with balance 0 at index -1?
Answer: C
The list 1, 0 has balances 1 and 0. Without the seed, the balance 0 at index 1 has nothing to pair with, so the answer is 0 and not 2.
Q4/5 The map stores an index for each running balance. Which index should it keep for the longest run?
Answer: B
The widest gap between two equal balances comes from the earliest one. Overwriting with the latest index shrinks every run.
Q5/5 A list holds 100,000 values of up to 1,000,000 each. What type should hold the prefix totals?
Answer: B
The largest total is 100,000,000,000, and a 32-bit int stops at 2,147,483,647. Use 64 bits for sums that can pass about two billion.
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.