Four problems about ranges on a line. The move: sort by start, carry one number, the furthest end so far, and decide each range with one comparison.
You work on the back end of a store, a chat app, a streaming app and a ride app. Four problems on this street come from them. Each one is about ranges on a line, and each looks like it needs a check of every range against every other.
With 100,000 sale windows, that is 9,999,900,000 checks of one window against another. After sorting by start, one pass is enough, and the pass carries a single number.
| Problem | The ranges are | The number you carry | What one comparison decides |
|---|---|---|---|
| Remove the covered slots | sale windows | the furthest end so far | a window whose end is not beyond it is covered |
| Split the log into the most chunks | the first to last place of each letter | the furthest last place in the open chunk | the chunk closes when the place reaches it |
| Fewest clips to cover the show | camera clips | how far the chosen clips reach | a clip that starts within reach can extend it |
| Next booking after each booking | trip bookings | none: the starts are sorted once | the first start at or after an end |
Three of the four carry a number. The last one shows that sorting by start is also the first step of a search.
Here is the second row on a small log. Each letter owns the range from its first place to its last place.
Exercise · Predict the output: Where the log is cut. The code stores the last place of every letter, then cuts the log whenever the place reaches the furthest last place seen in the open chunk. What does it print?
log = "mnomqnpp"
last = {}
for i, c in enumerate(log):
last[c] = i
sizes = []
start = 0
end = 0
for i, c in enumerate(log):
end = max(end, last[c])
if i == end:
sizes.append(i - start + 1)
start = i + 1
print(*sizes)The move has three steps, and you take them before you write code.
First, name the ranges. Some are given, and some you build, such as the span of a letter. Second, sort them by start. Third, write down the one number you carry and what a comparison with it decides.
After sorting by start, every range already read is summarised by one number: the furthest end reached so far. A new range is covered, joined or past a gap by one comparison of its ends with that number.
The covered slots show it. A slot is covered when its end is not beyond the furthest end of the slots that started before it.
Look at the slots 1 to 4, 3 to 6 and 2 to 8. Sorted by start they read 1 to 4, 2 to 8, 3 to 6. The furthest end goes 4, then 8, and the slot ending at 6 is covered. Two slots remain.
The sort needs one more rule. When two slots start at the same place, the longer one must come first. Then the shorter one is read after it and shows up as covered.
Exercise · Put it in order: Count the slots that are not covered. Arrange the lines into a function that counts the slots that are not covered by another slot. A slot [a, b] is covered by [c, d] when c <= a and b <= d.
def slots_not_covered(slots):
slots.sort(key=lambda s: (s[0], -s[1]))
count = 0
reach = -1
for start, end in slots:
if end > reach:
count += 1
reach = end
return count
slots.sort()
if end >= reach:Sort by start and carry the furthest end: a slot whose end is not beyond it is covered.
The Academy lesson Intervals merges overlapping ranges after sorting by start. Comparators in four languages sorts by two keys, and Lower and upper bound finds the first position at or after a value. This street does not teach those again. It changes three things about the merge.
The number becomes a goal. To cover the show with the fewest clips, you do not take every clip that extends the reach. Among all clips that start within the reach, you take the one with the furthest end, then repeat. If none extends the reach, a gap blocks the show and the answer is -1.
The ranges may be built. In the log problem nothing is given as a range. You build one for each letter, from its first place to its last place, and the cut falls where the furthest end is reached.
Sometimes you do not merge at all. The next booking after a given end is a search. Sort the starts once, with their indexes, and binary search for the first start at or after the end. A booking that starts exactly when another ends counts, so the search is a lower bound.
Exercise · Find the bug: The booking that starts on time. For each booking this finds the first booking that starts at or after its end, using a binary search over the sorted starts. It is right unless two bookings meet end to start. Which line is wrong?
def next_booking(bookings):
n = len(bookings)
order = sorted(range(n), key=lambda i: (bookings[i][0], i))
result = []
for start, end in bookings:
lo, hi = 0, n
while lo < hi:
mid = (lo + hi) // 2
if bookings[order[mid]][0] <= end:
lo = mid + 1
else:
hi = mid
result.append(order[lo] if lo < n else -1)
return resultThe clip problem has its own trap. Taking every clip that extends the reach looks like the same greedy rule, and the next block shows where it fails.
Do not take every clip that extends the reach. Take the one that ends farthest among those that start within it.
Exercise · Break it: Taking every clip that helps. This code sorts the clips by start and takes each clip that starts within the reach and ends beyond it. It returns -1 when the show is not covered. Find an input where it gives the wrong count.
def fewest_clips(clips, length):
clips.sort()
reach = 0
count = 0
for start, end in clips:
if start <= reach and end > reach:
reach = end
count += 1
return count if reach >= length else -1Solve them in this order. The first uses the covered test, the second builds its own ranges, the third turns the number into a goal, and the last is a search.
Before you code each problem, write two lines: the ranges and how you sort them, and the number you carry. If you cannot name a number, check whether the problem is a search over the sorted starts.
Give each problem about 20 minutes. Spend the first three on the two lines, and say them out loud as you would to an interviewer. Then list the edge cases before you run anything.
Three edge cases come back on every rung. Ranges can touch at one point, ranges can share a start, and nothing may extend the reach. Write one small test for each.
When a solution fails, look at the number you carry. Most wrong answers on this street come from the wrong sort order for equal starts, or from a comparison that is one too strict.
Checkpoint · Merging intervals
Q1/5 The slots are sorted by start. Which single number lets one comparison decide whether the next slot is covered?
Answer: B
A slot is covered when its end is not beyond the furthest end so far. The previous slot alone is not enough, because an earlier slot may reach farther.
Q2/5 Two sale windows start at the same minute: 1 to 2 and 1 to 4. To find the covered windows, which one is read first?
Answer: B
Read the longer window first. Then 1 to 2 ends before the furthest end 4 and is covered. Read in the other order, both windows are counted: 2 instead of 1.
Q3/5 The log is "abab". Each letter owns the range from its first place to its last place. What are the chunk sizes?
Answer: C
The letter a spans places 0 to 2 and the letter b spans places 1 to 3. The ranges overlap, so no cut is possible before place 3, and the only chunk has 4 letters.
Q4/5 The clips are 0 to 5, 1 to 6 and 5 to 10, and the show lasts 10 seconds. What is the fewest number of clips that cover it?
Answer: A
The clips 0 to 5 and 5 to 10 cover the whole show. Taking every clip that extends the reach would use all three.
Q5/5 The sorted starts are 1, 2, 2 and 5, and a booking ends at 2. Which start does the search for the next booking land on?
Answer: C
The search finds the first start at or after the end, a lower bound. A booking that starts at second 2 can follow a booking that ends at second 2.
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.