DEV Community

Academic Quant
Academic Quant

Posted on Originally published at academicquant.co.uk

Merge intervals: one nested booking turns 9 into 5

Say you've got three bookings, 1 to 10, 2 to 4 and 6 to 8. Together they cover 1 to 10, so the time covered is 9, but if your merge loop sets the end to e where it should take max(end, e) you'll get 5.

You sort by start and open a block at 1 to 10, and then 2 to 4 comes along. It overlaps, so you stretch the block, except the stretch sets the end to 4. When 6 to 8 turns up it starts after 4, so it looks like there's a gap, you close a block of 3 and open one of 2, and that's how four units of time disappear.

It's the interval mistake I see most. You won't catch it with the examples you'd try by hand, because in those the later booking always finishes later, and it only shows up when you've got one booking sitting right inside another.

def covered(bookings):
    total, cur = 0, None
    for s, e in sorted(bookings):
        if cur is None:
            cur = [s, e]
        elif s > cur[1]:              # there's a gap, so close the block
            total += cur[1] - cur[0]
            cur = [s, e]
        else:                         # they overlap or touch
            cur[1] = max(cur[1], e)
    return total + (cur[1] - cur[0] if cur else 0)

print(covered([(1, 10), (2, 4), (6, 8)]))   # 9
Enter fullscreen mode Exit fullscreen mode

You're paying O(n log n) for the sort and the sweep only looks at each booking once. Don't drop the last line either. The final block never meets a gap after it, so if you don't add it after the loop you've lost it.

When two bookings touch

Before you write the loop I'd ask what a booking actually means in your question. If they're half-open windows of time, 1 to 4 and 4 to 7 don't leave a gap. They cover 6 between them, and you'd merge whenever the next start is at or before the end you're holding (that's what s > cur[1] checks).

If they're whole days and you count both ends, everything moves by one. Days 1 to 4 and days 5 to 7 don't miss a day, so you'd merge when the next start's at most end + 1, and you'd count a block as end - start + 1. You get 7 days for those two.

Adding one range to a merged list

The follow-up you'll usually get next is a list that's already merged and sorted, and one new range you've got to fit in without sorting again. You don't need anything clever, just three loops one after the other, and it's linear:

def insert(blocks, new):
    s, e = new
    out, i, n = [], 0, len(blocks)
    while i < n and blocks[i][1] < s:      # ends before the new range
        out.append(blocks[i])
        i += 1
    while i < n and blocks[i][0] <= e:     # it touches, so you absorb it
        s, e = min(s, blocks[i][0]), max(e, blocks[i][1])
        i += 1
    out.append([s, e])
    return out + blocks[i:]                # everything to the right

print(insert([[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], [4, 8]))
# [[1, 2], [3, 10], [12, 16]]
Enter fullscreen mode Exit fullscreen mode

1 to 2 finishes before 4, so it goes straight through. The next three all start by 8 and they get folded into one block from 3 to 10. Then 12 to 16 just gets copied over.

Whenever I write a merge loop I try it on a short booking inside a long one (1 to 10 with 2 to 4 and 6 to 8) and on two that touch at a point (1 to 4 and 4 to 7). If you get both right you're usually fine. I've put a stepped trace you can click through, and a practice problem, at https://academicquant.co.uk/coding-intervals-merge?utm_source=devto&utm_medium=post&utm_campaign=devto-merge-intervals-nested-bug

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

This is the clearest version of the nested-interval trap I have seen, because the numbers make the loss visible: 1 to 10 with 2 to 4 and 6 to 8 inside it should cover 9, and the one-line mistake — cur[1] = e instead of max(cur[1], e) — quietly turns it into 5. What makes it nasty is exactly what you say: every example you would try by hand has later bookings finishing later, so the bug never shows up until a booking sits fully inside another one.

The habit I would add: test the merge against a brute-force check on random inputs — build the set of covered unit points and compare the totals. A random fuzzer finds the nested case in seconds, while a handful of hand-written cases almost never does. And the dropped-final-block bug is the same shape in disguise: the loop only settles a block when the next booking forces it to, so the last one needs the same care as the first.

One question on the touching case: you draw the half-open versus whole-day line clearly, but do interviewers usually state which convention they mean up front, or is spotting that the question is ambiguous part of the test — and would you answer by naming the assumption out loud before writing the loop?