Skip to main content

Intervals: Merge, Schedule, and Sweep

Interval problems look similar but ask different questions: union overlapping coverage, choose compatible jobs, or count simultaneous activity. Decide whether endpoints belong to the interval and what touching means before selecting a sort key. Merging by start, selecting by finish, and sweeping events rely on different invariants.

FrontendInterviews.dev Updated

Recognize the Pattern

  • Each item has a start and an end, and relationships depend on their ordering.
  • The task asks for combined coverage, a compatible subset, or maximum concurrent demand.
  • Equal endpoints can change the answer, so closed versus half-open semantics must be explicit.

Core Invariant

Sorted starts let each interval extend the last merged component or start a new one. A gap finalizes the preceding component.

Important Boundary

Closed coverage merges touching endpoints; half-open meetings can reuse a room at the same endpoint. Merged component count is not room count.

Closed intervals 1 to 3 and 2 to 6 overlap and merge into 1 to 6; 8 to 10 remains separate.
This is coverage merging. It is not a schedule that selects one of the overlapping intervals.

Choose endpoint semantics first

The same pair [1,2] and [2,3] joins under closed coverage but can use one room under half-open meeting semantics. Zero-duration meetings require a policy: an empty [t,t) consumes no time, while a closed [t,t] contains a point. Do not silently mix conventions.

TaskSort or event ruleBoundary
Merge closed rangesStart ascending.start <= lastEnd joins coverage.
Schedule half-open meetingsFinish ascending for maximum compatible count.nextStart >= previousEnd is compatible.
Count rooms for half-open meetingsTime ascending; departures before arrivals at ties.A room freed at t can be reused at t.
Count closed-interval overlapArrivals before departures at ties.Both intervals include their shared endpoint.

Merge into the last connected range

After sorting by start, every processed interval either extends the last merged component or begins a new one. If a new start exceeds the last end, no later interval can bridge backward into that component, so it is finalized. Otherwise extend with max(lastEnd, end), including contained intervals.

Template Assumptions

  • Finite closed numeric ranges [start, end] with start <= end; touching ranges merge.
  • Copies input intervals before numeric start sorting; returns new arrays and does not mutate caller data.
JavaScript Template
function mergeIntervals(intervals) {
  const sorted = intervals.map(([start, end]) => [start, end]);
  sorted.sort((a, b) => a[0] - b[0]);
  const merged = [];
  for (const [start, end] of sorted) {
    const last = merged[merged.length - 1];
    if (!last || start > last[1]) merged.push([start, end]);
    else last[1] = Math.max(last[1], end);
  }
  return merged;
}

Trace overlap, containment, and a gap

Incoming sorted rangeDecisionMerged coverage
[1,3]start first component[[1,3]]
[2,6]2 <= 3; extend[[1,6]]
[4,5]contained; end stays 6[[1,6]]
[8,10]8 > 6; new component[[1,6],[8,10]]

Step-by-Step: Extend coverage or start a new range

Step 1 / 5
101-3212-6424-5838-10
Incoming interval
[1,3]
Comparison
no previous range
Merged coverage
[[1,3]]

Start [1,3]

The inputs are already sorted by start in this example. The diagram shows their starts; labels show their complete ranges. Copy the first interval into the result.

Do not reuse merging for scheduling

  • For the largest compatible subset of unweighted jobs, earliest finish leaves the most room for future jobs. An exchange argument replaces a later-finishing first job with the earliest-finishing one without reducing the remaining compatible choices.
  • Weighted interval scheduling does not follow that greedy proof: taking many low-value jobs can lose to one valuable job. Use predecessor lookup and DP under that contract.
  • Room count is peak simultaneous demand, not the number of merged coverage components. Sweep starts and ends, or use a heap of active finishing times.
  • Insert Interval can scan in O(N) when existing ranges are already sorted and disjoint. Sorting from scratch discards that input advantage.
  • Employee Free Time merges occupied coverage across people, then reports finite gaps. Flatten-and-sort and k-way heap merge are alternatives with different input-order and memory costs.

Separate sorting, scanning, and copies

  • Merging N unsorted intervals conventionally costs O(N log N) comparison sorting plus O(N) scanning. This template copies the input and uses O(N) extra space including output.
  • The interval arrays returned are new arrays, so extending a merged endpoint does not mutate the caller's ranges.
  • An event sweep also typically costs O(N log N) sorting and O(N) event storage. Heap-based room counting uses O(N log K) scanning after start sorting, with at most K active rooms.

Mistakes and Counterexamples

Count merged components as the number of rooms.

Counterexample: Meetings [1,5] and [2,3] merge into one coverage component, but overlap in time and require two rooms.

Correction: Track active intervals with a sweep or heap; union coverage answers a different question.

Replace the merged end with a contained interval's end.

Counterexample: Merging [1,10] and [2,3] must keep end 10, not shorten the occupied range to end 3.

Correction: Extend with the maximum end value whenever the new interval overlaps the current component.

Select the earliest starting job for every scheduling goal.

Counterexample: Choosing [1,10] first blocks [2,3] and [3,4], although the two short half-open jobs form a larger compatible subset.

Correction: For unweighted maximum count, choose earliest finish; weighted value requires a different optimization proof.

Last-Minute Recap

  • Define endpoints and touching behavior.
  • Coverage, compatible selection, and concurrency are distinct goals.
  • Choose start sorting, finish sorting, or tie-aware events accordingly.
  • Include sorting and avoid unintended input mutation.

Explain It in an Interview

  1. Are intervals closed or half-open, and what happens at equal endpoints?
  2. Why does merging sort by start while unweighted scheduling chooses earliest finish?
  3. How would you count rooms instead of merging occupied coverage?

Ready to Apply This Pattern?

Before coding, explain why this pattern fits and what must stay true at each step. Start with an easier problem, then test that reasoning on a harder variation.

Ordered from Easy to Hard. Premium access requirements still apply.

References