Seven interview problems that keep a sorted record and answer many questions about it. The move: turn each question into one bound search, the first position at least x or the first above x.
You work on the back end of an auction site, a monitoring service and a video platform. The seven problems on this street each keep a sorted record. It may be times in order, group sizes, error rates that never fall, or a list that you build as you go.
Then many queries arrive. Each one asks where a value fits in the record, and one bound search answers it.
| Problem | The sorted record | One query | The answer from the bounds |
|---|---|---|---|
| Count elements within a score band | sorted bids | a band | upper(high) minus lower(low) |
| Value of a key at a past time | one key's times, in order | a time | the entry before the first later time |
| First day the error rate passes | rates that never fall | a limit as a fraction | the first day above the limit |
| Groups that reach the promotion goal | sorted group sizes | a boost | the groups at or above a rounded-up threshold |
| Closest k values to a target | sorted stops | a target | the start of the best window |
| Longest rising sequence of plays | the smallest tail of each length | a play | the first tail not below it |
| Envelopes that nest | tails of the heights | a height | the same, after a careful sort |
Read the last column. Lower bound is the first position at least x. Upper bound is the first position above x. Almost every answer is one of the two, or a small step from it.
Exercise · Predict the output: How many bids lie in each band?. The bids are sorted and can repeat. For each band, the code finds the first position at least low and the first position above high, and prints the differences. What does it print?
bids = [3, 5, 5, 5, 8, 9, 12]
out = []
for low, high in [(5, 5), (4, 9), (10, 11), (0, 20)]:
a, b = 0, len(bids)
while a < b:
mid = (a + b) // 2
if bids[mid] < low:
a = mid + 1
else:
b = mid
c, d = 0, len(bids)
while c < d:
mid = (c + d) // 2
if bids[mid] <= high:
c = mid + 1
else:
d = mid
out.append(str(c - a))
print(",".join(out))The move has two parts, and you make them before you write any code.
First, name the record, and check that it is sorted. For a key's history it is the times, because they arrive in order. For a rising sequence it is a list of tails that you keep sorted yourself.
Second, turn each query into one bound. The lower bound is the first position at least x, and the upper bound is the first position above x. The latest entry at or before a time t is the one right before the upper bound of t.
For a query value x, the flag at position i is false up to some point and true from there. The first true is a bound, and its neighbour before it is the floor.
For the times 2, 4, 4, 9, the latest time at or before 4 is position 2, and before 1 there is none. The upper bound of 4 is 3, so the floor is 3 minus 1.
The latest entry at or before a time is the one right before the upper bound of that time.
Exercise · Put it in order: The latest entry at or before t. Arrange the lines into a search that returns the position of the latest time that is at most t, or -1 when every time is later.
def last_at_most(times, t):
lo = 0
hi = len(times)
while lo < hi:
mid = lo + (hi - lo) // 2
if times[mid] > t:
hi = mid
else:
lo = mid + 1
return lo - 1
return loThe Academy lessons Searching over history and Lower and upper bound teach the bounds on one sorted list. The first-true template teaches the loop. This street does not teach them again. It changes four things.
The query picks the bound. A count in a band uses both: upper(high) minus lower(low). For the bids 3, 5, 5, 5, 8, 9, 12, the band 5 to 5 holds 3 bids. Mixing the two bounds is the common mistake, and it drops every repeated value.
The comparison must be exact. An error rate is a fraction, so compare fails over loads with a limit num over den by cross-multiplying: fails times den above num times loads. That reaches 10^9 times 10^6, which is 10^15 and needs 64 bits. Floats can fail: 999,999,999 over 1,000,000,000 is above 999,999,998 over 999,999,999, but doubles say it is not.
A threshold such as goal divided by boost is rounded up with integers too.
The record can be built as you go. For the longest rising sequence, keep the smallest tail for each length. Each play replaces the first tail that is not below it, or extends the list. Equal plays do not rise, so the bound must be strict: for 2, 2, 2 the answer is 1, and a non-strict bound gives 3.
A sort can hide the tie. For nested envelopes, sort by width, and for equal widths put the taller first. Then two envelopes of one width cannot chain. For 3 by 4 and 3 by 5 the answer is 1, and sorting both ascending gives 2.
Envelopes of equal width cannot nest. Sort equal widths with the taller first, so they cannot both extend the sequence.
Exercise · Find the bug: Equal plays do not rise. This returns the length of the longest strictly rising sequence of plays. It keeps the smallest tail for each length. It is wrong when plays repeat. Which line is wrong?
def longest_rising(plays):
tails = []
for x in plays:
lo, hi = 0, len(tails)
while lo < hi:
mid = (lo + hi) // 2
if tails[mid] <= x:
lo = mid + 1
else:
hi = mid
if lo == len(tails):
tails.append(x)
else:
tails[lo] = x
return len(tails)Exercise · Break it: Envelopes of equal width. This returns the longest chain of envelopes that each fit strictly inside the next, in both width and height. It sorts by width, then by height, and runs the rising-sequence search on the heights. Find an input where it gives the wrong length.
def longest_nest(boxes):
boxes = sorted(boxes, key=lambda b: (b[0], b[1]))
tails = []
for w, h in boxes:
lo, hi = 0, len(tails)
while lo < hi:
mid = (lo + hi) // 2
if tails[mid] < h:
lo = mid + 1
else:
hi = mid
if lo == len(tails):
tails.append(h)
else:
tails[lo] = h
return len(tails)Solve them in this order. The first is a plain count, the next four turn a query into a bound, and the last two build the sorted record as they go.
Before you code each problem, write two lines: what the sorted record is, and which bound, lower or upper, the query needs. If you cannot say whether the equal values count, decide it before you write the search.
Give each problem about 20 minutes. Spend the first three on the two lines, and say them aloud as you would to an interviewer. Then run your bound on a list with repeated values.
Four edge cases come back on almost every rung. A query is below everything, a query is above everything, a value is repeated, and the record is empty. Write one small test for each.
When a solution fails, print the lower and the upper bound of the query on a small list. Their difference must equal the number of equal values.
Checkpoint · Queries over history
Q1/5 What is the difference between the lower bound and the upper bound of x in a sorted list?
Answer: B
The two differ exactly when x appears in the list, and their difference is the number of copies of x.
Q2/5 The sorted bids are 3, 5, 5, 5, 8, 9, 12. How many bids lie in the band from 5 to 8, both included?
Answer: B
The first position above 8 is 5, and the first position at least 5 is 1. The difference is 4, for the bids 5, 5, 5 and 8.
Q3/5 How do you compare the fraction fails over loads with a limit num over den?
Answer: B
Floats can fail: 999,999,999 over 1,000,000,000 is above 999,999,998 over 999,999,999, but doubles say it is not. The cross products are whole numbers up to 10^15.
Q4/5 Plays repeat, and equal plays do not count as rising. Which bound do you use to place a play among the tails?
Answer: B
Replacing the first tail that is not below the play keeps equal plays from extending the sequence. For 2, 2, 2 the answer is 1.
Q5/5 Why are envelopes of equal width sorted with the taller first?
Answer: C
Sorting heights upwards would let 3 by 4 and 3 by 5 chain, which gives 2. Taller first keeps the answer at 1.
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.