Learn / Arrays

Intervals

An interval is a pair [start, end]. Sort the intervals by start, and then any interval can only overlap the one you finished just before it. One pass that keeps the last merged interval handles merging, inserting and counting overlaps.

How to recognise it

  • The input is a list of [start, end] pairs (meetings, bookings, ranges on a line).
  • The question asks to merge, insert, remove or count overlapping ranges.
  • Two ranges touching at one point should count as overlapping, or the problem says exactly when they do.

The idea in one picture

Draw each interval as a bar on a number line. Slide from left to right. Bars that touch or cross join into one longer bar, and a gap ends the bar you are building. Sorting by start is what lets you slide in one direction: once you pass a gap, nothing later can reach back over it.

The overlap test

For two intervals with a ≤ c, the pair [a, b] and [c, d] overlaps when c ≤ b. The merged interval is [a, max(b, d)]. Whether touching ends count (as in [1, 4] and [4, 5]) depends on the problem. Both problems here count them.

Template: merge after sorting

sort intervals by start
out = empty list
for each [s, e] in intervals:
    if out is not empty and s <= end of last in out:
        end of last in out = max(end of last in out, e)
    else:
        add [s, e] to out

Three phases for a sorted list

When the list is already sorted and separate, as in Insert Interval, split the walk into three phases:

PhaseConditionAction
Beforeinterval ends before the new one startscopy it
Overlapinterval starts no later than the new one endsgrow the new one
Aftereverything leftcopy it

Common mistakes

  • Forgetting to sort first, so an early interval appears after a later one and is never merged.
  • Setting the merged end to the new interval's end instead of the larger end.
  • Using < where the problem says touching intervals overlap, or <= where it says they do not.
  • Changing the input intervals while still reading them, then returning arrays that share memory with the input.

Problems

0 of 2 solved

Check yourself

Two intervals [a, b] and [c, d] with a <= c overlap exactly when...

After sorting by start, why is it enough to compare each interval with the last merged one only?

Merging [1, 10] with [2, 3], what should the end become?

In Insert Interval the list is already sorted and separate. What is the cost of inserting one interval?