SproutStackSproutStack home

Intervals

6 min readBeginner-friendlyFree to read

Read a little, play a little. No scary maths, and no rush.

Share:

Meetings that collide

Your calendar has [9, 11], [10, 12], and [13, 14]. The first two overlap — in real life you'd merge them into one busy block [9, 12]. Interval problems are exactly this: given a pile of ranges, fuse the overlapping ones. They show up in meeting rooms, server busy-times, and "minimum arrows to burst balloons."

The trick: sort first, then sweep

Unsorted intervals are chaos. Sorted by start time, the problem becomes a single left-to-right walk: keep a "current merged block," and for each next interval either extend it or seal it and start a new one.

def merge(iv):
    iv.sort()  # sort by start (then end)
    out = []
    for s, e in iv:
        if out and s <= out[-1][1]:      # overlaps? extend
            out[-1][1] = max(out[-1][1], e)
        else:                            # disjoint? start fresh
            out.append([s, e])
    return out

Trace [[1,3],[2,6],[8,10]]: sorted already; [2,6] overlaps [1,3] → [1,6]; [8,10] starts fresh → [[1,6],[8,10]].

The two follow-ups interviewers love

  • Insert interval: a new meeting arrives into an already-merged list. Walk until you find its place, merge with whatever it touches — same sweep, one pass.
  • Meeting rooms II: minimum rooms needed? Sort all starts and ends separately; sweep with a counter (+1 on start, −1 on end). The counter's peak is your answer.

Meeting rooms, traced

Meetings [0, 30], [5, 10], [15, 20]. Starts sorted: 0, 5, 15. Ends sorted: 10, 20, 30. Sweep through all of them in time order:

  • 0: a meeting starts, rooms in use 1.
  • 5: another starts, rooms 2.
  • 10: one ends, rooms 1.
  • 15: one starts, rooms 2.
  • 20 and 30: both end, rooms 0.

The peak was 2, so two rooms are needed.

Do touching intervals overlap?

Is [1, 2] overlapping [2, 3]? For merging ranges of numbers, usually yes, which is why the code above uses <=. For meetings, one ending at 2:00 and another starting at 2:00 do not conflict, so the test should be <, and in the room sweep an end at the same time as a start should be processed first. Ask which rule applies before coding; it is exactly the kind of clarifying question interviewers want.

Intersecting two lists

Given two sorted lists of free-time intervals, find the times both are free. Walk both with two pointers. The overlap of two intervals is from the later start to the earlier end, if that range is valid. Then advance whichever interval ends first, since it cannot overlap anything further in the other list.

Keeping the most intervals

"Remove the fewest intervals so none overlap" is solved greedily: sort by end time, keep each interval that starts after the last kept one ends, and skip the rest. Choosing the earliest finisher always leaves the most room for later intervals. The answer is the total minus the number kept.

Spotting interval problems

Look for pairs of start and end values: bookings, shifts, time ranges, ranges of numbers, or segments on a line. If the question asks about overlaps, gaps, coverage, or the most things happening at once, sort first and sweep.

Remember this

  • Sort by start, single sweep, extend-or-seal. O(n log n) from the sort, O(n) for the rest.
  • Overlap test is one line: next.start <= current.end.

Check your understanding

5 questions · first-try answers earn the most XP

1. Why must intervals be sorted by start before merging?
2. What is the overlap test when sweeping sorted intervals?
3. When merging, why do you take the maximum of the two end values rather than overwriting?
4. How do you find the minimum number of meeting rooms?
5. What is the total complexity of merging intervals?

My notes

Saved in this browser. Highlight a line above and save it, or write it in your own words.

Nothing saved yet. Your highlights will live here.

References

Finished reading?

Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.

Related chapters

Practice this pattern elsewhere

More problems to practise on external judges. Both links open the site home rather than a specific set, so you can pick problems for this pattern.

Spotted a mistake or want a topic covered? Report an issue

📬 An occasional email when new lessons land

New lessons and showdowns, no more than a few times a month. No spam, unsubscribe anytime. We store your email only to send the newsletter.