Intervals

How to merge overlapping intervals, test two intervals for overlap, count how many overlap at once, and what interviewers ask about interval problems.

14 minLesson 4 of 5
On this page
  1. Testing whether two intervals overlap
  2. Merging overlapping intervals
  3. Counting how many intervals overlap at once
  4. Variants of interval problems
  5. Pitfalls
  6. In the interview
  7. What to practise next

An interval is a pair of numbers, a start and an end, that describes a range such as a meeting, a booking, a video segment or a block of IP addresses. Interval problems ask you to merge ranges that overlap, to find gaps between them, or to count how many ranges are active at the same moment. Most of them are solved by sorting the intervals first and then making a single pass over them.

Without sorting, you would have to compare every interval with every other one, which takes O(n²) time. Once the intervals are sorted by start, each interval only has to be compared with the one block you are currently building.

Testing whether two intervals overlap

Two intervals can overlap in many different ways, but they can miss each other in only two: a ends before b starts, or b ends before a starts. The simplest overlap test checks for those two cases and negates the result.

Overlap a b Touching a b depends on the problem Apart a b a.end < b.start
Two intervals miss each other only when one ends before the other starts. Every other arrangement is an overlap.
// Touching counts as overlapping here. Use < instead of <= if it should not.
function overlaps(a, b) {
  return a[0] <= b[1] && b[0] <= a[1];
}
# Touching counts as overlapping here. Use < instead of <= if it should not.
def overlaps(a, b):
    return a[0] <= b[1] and b[0] <= a[1]

Whether two intervals that touch at one point overlap is decided by the problem, not by the algorithm. In a calendar, 14–16 and 16–17 form one continuous busy period, so they should be merged. For room bookings, a meeting that ends at 16 does not block a meeting that starts at 16. Read the statement for this rule, choose < or <= once, and use the same choice everywhere in your solution.

Merging overlapping intervals

To merge intervals, sort them by start and keep one open block, which is the merged interval you are currently extending. For each next interval, compare its start with the block's end. If the interval starts at or before the end of the block, it overlaps the block, so you set the block's end to the larger of the two ends. If it starts after the block's end, there is a gap, so you close the block and open a new one.

This works because of the sort order. Every interval that comes later starts at or after the current block's start, so it can only reach back as far as the last block. Earlier blocks ended before the current one started, and no later interval can touch them.

The trace below merges five meetings: 13–15, 9–11, 10–12, 16–17 and 14–16. After sorting by start they are 9–11, 10–12, 13–15, 14–16 and 16–17, and touching counts as overlapping.

Merge five meetings into busy blocksUse the arrows or ← → keys
sort meetings by startbusy = [first meeting]for each next meeting (start, end):  last = the final block in busy  if start <= last.end: last.end = max(last.end, end)  else: add (start, end) as a new block
  1. meetings
    09–11i
    110–12
    213–15
    314–16
    416–17
    busy
    09–11
    block end
    11

    1The meetings are sorted by start, and the first meeting becomes the first block.

  2. meetings
    09–11
    110–12i
    213–15
    314–16
    416–17
    busy
    09–12
    block end
    12

    2The meeting 10–12 starts before the block ends at 11, so the block's end is stretched to 12.

  3. meetings
    09–11
    110–12
    213–15i
    314–16
    416–17
    busy
    09–12
    113–15
    block end
    15

    3The meeting 13–15 starts after 12, so there is a gap and it opens a new block.

  4. meetings
    09–11
    110–12
    213–15
    314–16i
    416–17
    busy
    09–12
    113–16
    block end
    16

    4The meeting 14–16 starts inside the second block, so that block's end is stretched to 16.

  5. meetings
    09–11
    110–12
    213–15
    314–16
    416–17i
    busy
    09–12
    113–17
    block end
    17

    5The meeting 16–17 starts exactly when the block ends. Touching counts as overlapping here, so the block's end is stretched to 17.

  6. meetings
    09–11
    110–12
    213–15
    314–16
    416–17
    busy
    09–12
    113–17
    blocks
    2

    6Five meetings have become two busy blocks, found in one pass after sorting.

1 / 6
function mergeBusy(meetings) {
  if (meetings.length === 0) return [];
  const sorted = [...meetings].sort((a, b) => a[0] - b[0]);
  const busy = [[...sorted[0]]];
  for (const [start, end] of sorted.slice(1)) {
    const last = busy[busy.length - 1];
    if (start <= last[1]) {
      last[1] = Math.max(last[1], end); // overlaps or touches: stretch
    } else {
      busy.push([start, end]);          // gap: new block
    }
  }
  return busy;
}
 
mergeBusy([[13, 15], [9, 11], [10, 12], [16, 17], [14, 16]]);
// [[9, 12], [13, 17]]
def merge_busy(meetings):
    if not meetings:
        return []
    ordered = sorted(meetings, key=lambda m: m[0])
    busy = [list(ordered[0])]
    for start, end in ordered[1:]:
        last = busy[-1]
        if start <= last[1]:
            last[1] = max(last[1], end)  # overlaps or touches: stretch
        else:
            busy.append([start, end])    # gap: new block
    return busy
 
merge_busy([[13, 15], [9, 11], [10, 12], [16, 17], [14, 16]])
# [[9, 12], [13, 17]]

The code copies the first interval so that stretching the block does not change the caller's data.

TimeO(n log n)
SpaceO(n)

Sorting dominates. The sweep itself is O(n), and the output can hold all n intervals.

Counting how many intervals overlap at once

Some problems ask for the maximum number of intervals that are active at the same moment. The standard example is the number of meeting rooms needed for a list of meetings. Merging does not answer this, because a merged block hides how many meetings are inside it.

The technique is to turn each interval into two events: a +1 event at its start and a −1 event at its end. You sort all events by time and walk through them with a counter that goes up on a start and down on an end. The largest value the counter reaches is the answer. When a start and an end happen at the same time, process the end first if the problem allows a room to be reused at the moment a meeting ends.

The trace below uses the meetings 9–12, 10–11, 11–13 and 13–14. A + after the time marks a start and a − marks an end.

Count rooms with a sweep over eventsUse the arrows or ← → keys
events = (start, +1) and (end, −1) for each meetingsort events by time; at a tie, −1 before +1for each event:  inUse += change; most = max(most, inUse)
  1. events
    09 +i
    110 +
    211 −
    311 +
    412 −
    513 −
    613 +
    714 −
    inUse
    1
    most
    1

    1At time 9 the meeting 9–12 starts, so one room is in use.

  2. events
    09 +
    110 +i
    211 −
    311 +
    412 −
    513 −
    613 +
    714 −
    inUse
    2
    most
    2

    2At time 10 the meeting 10–11 starts while 9–12 is still running, so two rooms are in use.

  3. events
    09 +
    110 +
    211 −i
    311 +
    412 −
    513 −
    613 +
    714 −
    inUse
    1
    most
    2

    3At time 11 the end event sorts first, so the meeting 10–11 leaves and one room is freed.

  4. events
    09 +
    110 +
    211 −
    311 +i
    412 −
    513 −
    613 +
    714 −
    inUse
    2
    most
    2

    4Still at time 11, the meeting 11–13 takes the freed room, so two rooms are in use and the count never reaches three.

  5. events
    09 +
    110 +
    211 −
    311 +
    412 −i
    513 −
    613 +
    714 −
    inUse
    1
    most
    2

    5At time 12 the meeting 9–12 ends, leaving one room in use.

  6. events
    09 +
    110 +
    211 −
    311 +
    412 −
    513 −i
    613 +
    714 −
    inUse
    0
    most
    2

    6At time 13 the meeting 11–13 ends first, leaving no rooms in use.

  7. events
    09 +
    110 +
    211 −
    311 +
    412 −
    513 −
    613 +i
    714 −
    inUse
    1
    most
    2

    7Still at time 13, the meeting 13–14 starts, so one room is in use again.

  8. events
    09 +
    110 +
    211 −
    311 +
    412 −
    513 −
    613 +
    714 −i
    inUse
    0
    most
    2

    8At time 14 the meeting 13–14 ends. The highest count was 2, so two rooms are enough.

1 / 8
function roomsNeeded(meetings) {
  const events = [];
  for (const [start, end] of meetings) {
    events.push([start, 1], [end, -1]);
  }
  // by time; at a tie, -1 (an end) sorts before +1 (a start)
  events.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
  let inUse = 0;
  let most = 0;
  for (const [, change] of events) {
    inUse += change;
    most = Math.max(most, inUse);
  }
  return most;
}
 
roomsNeeded([[9, 12], [10, 11], [11, 13], [13, 14]]); // 2
def rooms_needed(meetings):
    events = []
    for start, end in meetings:
        events.append((start, 1))
        events.append((end, -1))
    # tuples sort by time, then by change, so -1 (an end) comes before +1
    events.sort()
    in_use = most = 0
    for _, change in events:
        in_use += change
        most = max(most, in_use)
    return most
 
rooms_needed([[9, 12], [10, 11], [11, 13], [13, 14]])  # 2
TimeO(n log n)
SpaceO(n)

Sorting the 2n events dominates, and the events themselves take O(n) space.

Variants of interval problems

Inserting one interval into a sorted list

When the list is already sorted and its intervals do not overlap, adding a new interval needs no sort. You copy every interval that ends before the new one starts, then merge the new interval with every interval that overlaps it by taking the smallest start and the largest end, and finally copy the intervals that start after the merged one ends. This is three loops over the list, so it takes O(n) time. Sorting again would be correct but would cost O(n log n) and would show that you missed the sorted input.

Finding gaps and free time

A gap is the space between two merged blocks, so the usual solution is to merge first and then read the gaps off the result. For each pair of neighbouring blocks, the gap runs from the end of the first block to the start of the second. Problems such as finding the common free time of several people work the same way: put every person's busy intervals into one list, merge it, and report the gaps between the merged blocks. If the problem asks for free time inside a fixed window such as a working day, also report the space before the first block and after the last one.

Intersecting two sorted lists

When you have two sorted lists of non-overlapping intervals and want the ranges covered by both, use two pointers, one for each list. The intersection of the current pair is from the larger of the two starts to the smaller of the two ends, and it exists only if that start is not after that end. After handling the pair, advance the pointer of the interval that ends first, because that interval cannot overlap anything further along in the other list. This runs in O(n + m) time.

Keeping the most non-overlapping intervals

The question "what is the largest number of intervals I can keep without any two overlapping" is a greedy problem, and it needs a different sort order. You sort by end time and keep an interval whenever it starts at or after the end of the last interval you kept. Sorting by start fails here, because one very long interval that starts early would block many short ones. The same sort-by-end idea answers "how many intervals must I remove so that none overlap", which is the total minus the number you can keep. The reasoning for why this is correct is in Greedy Algorithms.

When sorting and sweeping does not apply

The sort-and-sweep approach assumes that you have all the intervals up front. If intervals arrive one at a time and you must answer overlap questions after each one, re-sorting every time is too slow. Then you need a structure that stays ordered as it changes, such as a balanced tree keyed by start, or an interval tree. Interview problems of this kind usually say "design a class" and expect you to keep a sorted structure. Intervals in more than one dimension, such as rectangles, also need a different approach.

Pitfalls

In the interview

The signals for an interval problem are a list of pairs that represent ranges, together with words such as "overlap", "merge", "conflict", "free time", "meeting rooms" or "at the same time". If the statement asks for the number of simultaneous intervals, use the event sweep. If it asks for merged ranges or gaps, sort by start. If it asks for the most intervals you can keep, sort by end. Say which sort key you choose and why before you write any code.

Before coding, ask whether touching intervals count as overlapping, whether the input is already sorted, and whether the intervals can be empty or have an end before the start. Interviewers pay close attention to whether you ask about the touching case, since it changes a < into a <=.

Questions to expect:

  • "Why do you sort by start and not by end?" When merging, sorting by start guarantees that a new interval can only overlap the last block, so one pass is enough. Sorting by end is the right choice for the problem of keeping the most non-overlapping intervals, where the interval that finishes first leaves the most room for the rest.
  • "What is the time and space complexity?" The time is O(n log n) because of the sort, and the sweep adds only O(n). The space is O(n) for the output or the events, or O(1) extra if the problem lets you merge in place.
  • "How would you find the number of meeting rooms another way?" Sort the meetings by start and keep a min-heap of end times. For each meeting, if the earliest end in the heap is at or before the new start, remove it, and then push the new end. The largest size the heap reaches is the number of rooms. This is also O(n log n) and it is the version that assigns meetings to rooms.
  • "What if the input is already sorted?" Merging then takes O(n) time with no sort. Inserting one interval into a sorted, non-overlapping list is also O(n).
  • "What if intervals are added over time?" Keep the non-overlapping blocks in a sorted structure with O(log n) search, such as a balanced tree. For each new interval, find the blocks it touches, merge them into one and replace them. Re-sorting a list on every insertion would cost O(n log n) each time.
  • "What if the numbers are very large, like timestamps?" Nothing changes, because the algorithm compares values and never indexes by them. A counting array indexed by time would fail here, which is a reason to prefer events.
Quick check

Merge [1, 4], [2, 3], [5, 7] and [6, 9], with touching counted as overlapping. What is the result?

The meetings are 1–5, 2–6 and 5–8, and a room can be reused the moment a meeting ends. How many rooms are needed?

Which problem should be solved by sorting the intervals by end time instead of by start time?

What to practise next

The sort-by-end problem is explained in Greedy Algorithms, and the pointer technique for intersecting two lists is covered in Two Pointers.