PROBLEM-SOLVING PATTERNS / ALGORITHM BRIEF

Intervals

Interval problems deal with ranges [start, end]: meetings, bookings, time slots, number ranges.

IntermediatePhase 03 / Topic 8 of 10Mental modelComplexityEdge cases
01

Overview

Interval problems deal with ranges [start, end]: meetings, bookings, time slots, number ranges. Almost all of them start the same way: sort by start time (or end time), then scan once while comparing each interval with the previous one or with a running boundary.

Two intervals [a, b] and [c, d] overlap when a <= d and c <= b. Merging, inserting, counting rooms, and removing overlaps are all variations of this check combined with the right sort order and a greedy choice.

Booking meeting rooms

Sort meetings by start time. If the next meeting starts before the current one ends, they conflict and need different rooms, or, if you are merging calendars, they become one longer busy block.

02

When to use it

  • Input is a list of ranges, time slots, or segments.
  • The problem mentions overlap, merge, conflict, free time, rooms, or arrows.
  • You need the minimum number of resources to host all intervals.
  • You need the maximum number of non-overlapping intervals.
03

Problem patterns it solves

Merge overlapping intervals

Recognize it when: combine overlapping ranges into disjoint blocks; sort by start.

  • 56. Merge Intervals
  • 57. Insert Interval
  • 986. Interval List Intersections
  • 759. Employee Free Time
Maximum non-overlapping (greedy by end)

Recognize it when: remove the fewest intervals, or pick the most, so none overlap.

  • 435. Non-overlapping Intervals
  • 452. Minimum Number of Arrows to Burst Balloons
  • 646. Maximum Length of Pair Chain
Minimum resources (rooms)

Recognize it when: maximum number of overlapping intervals at any time.

  • 253. Meeting Rooms II
  • 2406. Divide Intervals Into Minimum Number of Groups
  • 1094. Car Pooling
Conflict check

Recognize it when: can one person attend all meetings.

  • 252. Meeting Rooms
  • 729. My Calendar I
Coverage and gaps

Recognize it when: is a range fully covered; find missing ranges.

  • 1288. Remove Covered Intervals
  • 228. Summary Ranges
  • 1024. Video Stitching
04

Where it is used in real software

Calendar applications

Google Calendar and Outlook merge busy blocks from multiple calendars to show free time and detect conflicts.

Resource allocation

Cloud schedulers compute the peak number of concurrent jobs to size machine pools, the meeting rooms problem.

Genome and time-series databases

Interval trees index genomic regions and time ranges for fast overlap queries.

IP address ranges

Firewalls merge overlapping CIDR ranges into minimal rule sets.

05

Key terms

Overlap
[a, b] and [c, d] overlap if a <= d and c <= b (use < for half-open intervals).
Merge
Replace overlapping intervals with [min start, max end].
Sort by start
Used for merging, inserting, and coverage.
Sort by end
Used for the greedy maximum set of non-overlapping intervals.
Sweep line
Process start and end events in order with a running count.
06

Merge intervals algorithm

  1. 1
    Sort by start

    Overlapping intervals now sit next to each other.

  2. 2
    Start the result with the first interval

    It is the current open block.

  3. 3
    Compare each next interval with the last block

    If next.start <= last.end, they overlap.

  4. 4
    Overlap: extend

    last.end = max(last.end, next.end). The max matters when one interval contains another.

  5. 5
    No overlap: start a new block

    Push the interval to the result.

07

Merge [[1, 3], [2, 6], [8, 10], [15, 18], [9, 12]]

After sorting by start: [1, 3], [2, 6], [8, 10], [9, 12], [15, 18]

Step 1 / 5
IntervalLast blockOverlap?Result after
[1, 3]--[1, 3]
[2, 6][1, 3]2 <= 3 yes[1, 6]
[8, 10][1, 6]8 <= 6 no[1, 6], [8, 10]
[9, 12][8, 10]9 <= 10 yes[1, 6], [8, 12]
[15, 18][8, 12]15 <= 12 no[1, 6], [8, 12], [15, 18]

NOWInterval: [1, 3] | Last block: - | Overlap?: - | Result after: [1, 3]

Three disjoint blocks. Sorting costs O(n log n) and the scan is O(n).

08

Implementation

function merge(intervals) {  intervals.sort((a, b) => a[0] - b[0]);  const result = [intervals[0].slice()];  for (let i = 1; i < intervals.length; i++) {    const last = result.at(-1);    const [start, end] = intervals[i];    if (start <= last[1]) last[1] = Math.max(last[1], end);    else result.push([start, end]);  }  return result;} // 435: minimum removals = n - maximum non-overlapping set (greedy by end)function eraseOverlapIntervals(intervals) {  intervals.sort((a, b) => a[1] - b[1]);  let kept = 0, lastEnd = -Infinity;  for (const [start, end] of intervals) {    if (start >= lastEnd) {      kept++;      lastEnd = end; // the earliest finish leaves the most room    }  }  return intervals.length - kept;} // 253: minimum meeting rooms with two sorted arraysfunction minMeetingRooms(intervals) {  const starts = intervals.map((i) => i[0]).sort((a, b) => a - b);  const ends = intervals.map((i) => i[1]).sort((a, b) => a - b);  let rooms = 0, best = 0, e = 0;  for (let s = 0; s < starts.length; s++) {    if (starts[s] < ends[e]) rooms++; // needs a new room    else e++;                         // reuse a room that just freed up    best = Math.max(best, rooms);  }  return best;}
09

Complexity and performance

SortO(n log n)

Dominates most interval solutions.

ScanO(n)

Single pass after sorting.

Meeting rooms with heapO(n log n)

Heap of end times.

Insert into sorted listO(n)

No sort needed.

10

Trade-offs

Sort by start vs end

Merging needs start order to bring overlaps together. Selecting the most non-overlapping intervals needs end order, because finishing earliest leaves the most room.

Heap vs two arrays for rooms

Both are O(n log n). Two sorted arrays is shorter; the heap also tells you which meeting ends next.

Closed vs half-open

Whether [1, 2] and [2, 3] overlap depends on the problem; check with an example before coding.

11

Variants and related techniques

Interval intersections

Two pointers over two sorted lists: overlap is [max(starts), min(ends)] when valid; advance the one that ends first.

Sweep line

Turn intervals into +1 / -1 events; the running maximum is the peak overlap.

Interval tree / TreeMap

For online insertions and overlap queries, use a balanced tree keyed by start (My Calendar).

12

Common mistakes

  • Forgetting max when merging.

    Fix: [1, 10] and [2, 3] merge to [1, 10], not [1, 3].

  • Mutating the input intervals.

    Fix: Copy the first interval when building results if the caller needs the input.

  • Comparator overflow in Java.

    Fix: Use Integer.compare(a[0], b[0]) rather than a[0] - b[0].

13

Interview questions

Why sort by end time for the maximum non-overlapping set?

Picking the interval that ends earliest leaves the most room for the rest. An exchange argument shows any optimal solution can swap its first interval for the earliest-ending one without losing count.

How do you find the minimum number of meeting rooms?

It equals the maximum number of meetings overlapping at any moment. Compute it with a min-heap of end times or a sweep over sorted start and end times.

14

Practice problems

ProblemDifficultyWhat it trains
252. Meeting RoomsEasyConflict check.
56. Merge IntervalsMediumSort and merge.
57. Insert IntervalMediumThree phases.
435. Non-overlapping IntervalsMediumGreedy by end.
452. Minimum Number of Arrows to Burst BalloonsMediumGreedy by end.
253. Meeting Rooms IIMediumHeap or sweep.
986. Interval List IntersectionsMediumTwo pointers.