Seven interview problems about sorted data. The move: turn each question into a flag that flips from false to true once, then find the first true.
You work on the back end of a bank, a monitoring service and a shop. The seven problems on this street look different. One finds an id, one finds a letter, one takes a square root. Each of them asks the same thing about sorted data: where does the answer begin?
Write each question as a flag. The flag is false for the first positions of the data and true from some position on. The answer is the first true.
| Problem | The flag at position i | The answer |
|---|---|---|
| Find an id in a sorted index | ids[i] >= query | that position, if the id is equal to the query |
| Smallest letter greater than the key | letters[i] > key | that position, or the first letter if none |
| Closest element to a target | prices[i] >= budget | the closer of that price and the one before it |
| Integer square root | i * i > n | i - 1 |
| First and last occurrence of a code | codes[i] >= x, then codes[i] >= x + 1 | the first position, and one before the second |
| First day the spend limit is reached | running total up to i >= limit | that day |
| Search in a list of unknown length | entries[i] >= target | that position, if the entry is equal |
Read the last column. Each answer is the first true, or a small step from it. That is why one template covers all seven.
Exercise · Predict the output: The smallest letter greater than each key. The code finds the first letter strictly greater than each key, and wraps to the first letter when there is none. What does it print?
letters = "cfjp"
out = ""
for key in "acjz":
lo, hi = 0, len(letters)
while lo < hi:
mid = (lo + hi) // 2
if letters[mid] > key:
hi = mid
else:
lo = mid + 1
out += letters[lo % len(letters)]
print(out)The move has two parts, and you make them before you write any code.
First, write the flag as one comparison that is false, then true, and never goes back. For an id it is ids[i] >= query. For a running total it is total[i] >= limit. Say it aloud as a sentence, and check that a bigger i can only make it more true.
Second, run the first-true search from the Academy on it. The window is [lo, hi), where hi is one past the last position that can be the answer.
At every step, the flag is false at every position before lo and true at every position from hi on. When lo meets hi, the answer is lo, and lo equal to the length means that no position is true.
The same loop answers every row of the table. Only the comparison inside it changes.
Find the first id at least the query: the middle decides whether to look left or right, and lo ends at the answer.
Exercise · Find the bug: The day the limit is reached. The list holds the running totals of daily spend. This returns the first day whose total reaches the limit, or -1 when none does. It is wrong when a total is equal to the limit. Which line is wrong?
def first_day(totals, limit):
lo, hi = 0, len(totals)
while lo < hi:
mid = (lo + hi) // 2
if totals[mid] > limit:
hi = mid
else:
lo = mid + 1
return lo if lo < len(totals) else -1The Academy lessons The first-true template and Lower and upper bound teach the loop on a list of flags and on a sorted array. This street does not teach them again. It changes four things.
There are many queries. A list of 100,000 ids with 100,000 queries costs up to 10,000,000,000 comparisons by scanning. The search takes 17 steps per query, so 1,700,000 in all.
The flag may not be on an array. For the square root there is nothing to index. The values 0 to n are the data, and the flag is i * i > n.
The product is the trap: 46,341 times 46,341 is 2,147,488,281, which is above the 32-bit limit of 2,147,483,647. Use a 64-bit type for mid * mid.
The sorted values may be computed. A running total is sorted only because spend is never negative. A day with zero spend repeats the total, so the first true matters: it gives the first day the limit is reached, not the last. The totals can pass 32 bits, so keep them in 64.
The length may be unknown. Probe positions 1, 2, 4, 8 and so on until the entry there is at least the target or past the end. A target at position 100,000 takes 17 doublings to reach 131,072. Then search between the last two probes with the usual loop.
Exercise · Put it in order: The integer square root. Arrange the lines into a search that returns the largest s with s * s at most n. The flag is mid * mid > n.
def int_root(n):
lo = 0
hi = n + 1
while lo < hi:
mid = lo + (hi - lo) // 2
if mid * mid > n:
hi = mid
else:
lo = mid + 1
return lo - 1
return loA strict flag skips the day whose total is exactly the limit. Use at least, because meeting a limit counts as reaching it.
Solve them in this order. The first four have a flag you can write in one line, and the last three change what the sorted data is.
Before you code each problem, write two lines: the flag at position i, and what the answer is when you find the first true. If you cannot write the flag as one comparison, the data is not sorted for this question yet.
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 name the edge cases before you run anything.
Four edge cases come back on almost every rung. The target is smaller than everything, it is larger than everything, it is equal to a repeated value, and the answer is one past the end. Write one small test for each of them.
When a solution fails, test the flag on its own. Print it for every position of a small input and check that it reads false, false, true, true, with no return to false.
Checkpoint · Search in order
Q1/5 What must be true of a flag before you can find its first true with the loop?
Answer: B
The loop rules out half of the window at every step. That works only when a true flag can never be followed by a false one.
Q2/5 You need the smallest letter strictly greater than the key, and the key is equal to a letter in the list. Which flag do you use?
Answer: B
A strict flag skips the letter that is equal to the key. The flag with >= would return that letter itself.
Q3/5 After the search for the smallest greater letter, lo is equal to the length of the list. What is the answer?
Answer: C
No letter is greater than the key, and the problem says to wrap. The position one past the end maps to position 0.
Q4/5 Why does the integer square root search use a 64-bit type for mid * mid?
Answer: C
The value 46,341 squared is 2,147,488,281, which is above 2,147,483,647. A 32-bit product wraps to a wrong flag.
Q5/5 A sorted file has no known length. How do you find where to search?
Answer: B
Doubling reaches the right range in about log n probes. The usual first-true search then runs between the last two probes.
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.