Objectives and sequence#
- Turn interval endpoints into ordered events and define the active-state meaning.
- Group all changes at an equal coordinate before evaluating a post-coordinate state.
- Use half-open [start,end) intervals to make touching endpoints unambiguous.
- Distinguish peak overlap from total union length instead of treating them as the same query.
Strict prerequisites
Recommended before
Recognition boundaries#
Signals
- Many intervals contribute state changes at ordered positions or times.
- The question asks for a peak active count, capacity violation, covered length, or another aggregate between event coordinates.
- Processing endpoints together is simpler than comparing every interval pair.
Anti-clues
- The task asks to merge and return the actual intervals only; a sorted interval scan is usually simpler.
- Coordinates arrive online and must support arbitrary updates and queries; a static sorted sweep is not enough.
- The state depends on two spatial dimensions or geometric intersections; this one-dimensional event model does not cover it.
From baseline to method#
Simple baseline: For peak overlap, compare each interval with every other interval or sample every coordinate. For union length, repeatedly test coverage at individual positions. Pair comparison is O(n²), and coordinate sampling is invalid for large or continuous domains.
- Represent each nonempty half-open interval [start,end) with +1 at start and -1 at end.
- Sort event coordinates and combine all deltas at the same coordinate so input order cannot decide ties.
- Before applying the delta at x, add x-previousX to union length exactly when the old active count is positive.
- Apply the grouped delta, then update peak from the new active count. Half-open intervals ending at x no longer overlap intervals beginning at x.
- Peak overlap and union length share events but answer different questions: one maximizes state, the other integrates positive coverage across coordinate gaps.
Worked example#
For half-open intervals, return both peak overlap and total covered length.
- Input
intervals = [[1,4), [2,6), [6,8), [9,11)]- Contract
- Endpoints are integers, start ≤ end, zero-length intervals contribute nothing, and intervals use [start,end) semantics.
- Expected
peakOverlap = 2, unionLength = 9
Trace summary: For each sorted coordinate, first add the preceding gap when active is positive, then apply that coordinate's grouped start/end delta and update the peak.
| Step | State | Explanation |
|---|---|---|
| x=1 | gap=0, delta=+1, active=1, peak=1, union=0 | Coverage begins at 1. |
| x=2 | gap=1 covered, delta=+1, active=2, peak=2, union=1 | The second interval overlaps the first on [2,4). |
| x=4 | gap=2 covered, delta=-1, active=1, peak=2, union=3 | The first interval ends, but coverage continues. |
| x=6 | gap=2 covered, grouped delta=(-1+1)=0, active=1, peak=2, union=5 | One interval ends exactly as another begins; half-open grouping creates no double overlap and no coverage gap. |
| x=8 | gap=2 covered, delta=-1, active=0, peak=2, union=7 | Coverage stops after [6,8). |
| x=9 | gap=1 uncovered, delta=+1, active=1, peak=2, union=7 | The uncovered gap [8,9) contributes no length. |
| x=11 | gap=2 covered, delta=-1, active=0, peak=2, union=9 | The last covered segment adds two. |
Pseudocode and tested references#
The pseudocode treats coordinates and the delta map abstractly. The tested references use integer/long coordinates, group equal coordinates in an ordered map, and return a named pair rather than relying on endpoint sort order.
summarizeIntervals(intervals):
delta = empty map from coordinate to integer
for [start, end) in intervals:
if start == end: continue
delta[start] += 1
delta[end] -= 1
active = 0; peak = 0; unionLength = 0; previous = none
for x in sorted(delta.keys):
if previous exists and active > 0: unionLength += x - previous
active += delta[x]
peak = max(peak, active)
previous = x
return (peak, unionLength)def summarize_intervals(intervals):
delta = {}
for start, end in intervals:
if start > end:
raise ValueError("expected start <= end")
if start == end:
continue
delta[start] = delta.get(start, 0) + 1
delta[end] = delta.get(end, 0) - 1
active = peak = union_length = 0
previous = None
for coordinate in sorted(delta):
if previous is not None and active > 0:
union_length += coordinate - previous
active += delta[coordinate]
peak = max(peak, active)
previous = coordinate
return {"peak_overlap": peak, "union_length": union_length}import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public final class SweepLineReference {
public record Interval(long start, long end) {}
public record Summary(int peakOverlap, long unionLength) {}
public static Summary summarizeIntervals(List<Interval> intervals) {
Map<Long, Integer> delta = new TreeMap<>();
for (Interval interval : intervals) {
if (interval.start() > interval.end()) {
throw new IllegalArgumentException("expected start <= end");
}
if (interval.start() == interval.end()) continue;
delta.merge(interval.start(), 1, Integer::sum);
delta.merge(interval.end(), -1, Integer::sum);
}
int active = 0;
int peak = 0;
long unionLength = 0;
Long previous = null;
for (Map.Entry<Long, Integer> event : delta.entrySet()) {
long coordinate = event.getKey();
if (previous != null && active > 0) unionLength += coordinate - previous;
active += event.getValue();
peak = Math.max(peak, active);
previous = coordinate;
}
return new Summary(peak, unionLength);
}
}- Time
- O(n log n) to build and order at most 2n event coordinates; the sweep itself is O(n).
- Space
- O(n) for grouped events.
- Assumptions
- Intervals are static, half-open, and use integer coordinates; accumulated union length fits Python integer or Java long in the references.
Failure modes and edges#
Edge cases
- Empty input returns peak 0 and union length 0.
- A zero-length [x,x) interval contributes neither activity nor length.
- Touching [a,b) and [b,c) intervals have continuous union but do not overlap each other.
- Duplicate intervals increase peak multiplicity but not union length.
- Nested intervals change peak while leaving the outer union boundary unchanged.
- Negative coordinates work because only sorted order and differences matter.
Wrong approaches
Sort raw starts before ends at a tie
That temporarily counts touching half-open intervals as overlapping. Grouping equal-coordinate deltas removes event-order dependence.
Add length after applying the current delta
The gap ending at x was covered by the state before x, not by the state after x.
Infer union length from the peak
Peak is a maximum count; union length is the measure of all segments with positive active state. Neither determines the other.
Enumerate every coordinate
It depends on coordinate magnitude and fails for non-unit or continuous coordinate domains.
Three-stage hint ladder#
Reveal hint 1
Observation: the active set can change only at a start or end coordinate.
Reveal hint 2
Invariant/data structure: group a +1/-1 delta map by coordinate; active describes the entire gap until the next event.
Reveal hint 3
Transition/pseudocode: add the previous gap when active>0, apply the grouped delta at x, update peak, and advance previous=x.
Narrated reasoning
I will state [start,end) first so equal endpoints have one precise meaning. Both answers can share event deltas, but I must update them at different moments. The current active count covers the gap leading up to x, so I add that gap before changing active. I combine every delta at x before measuring the new active count, preventing input order from manufacturing a tie overlap. I will test touching, duplicate, nested, empty, and zero-length intervals.
Reasoning checkpoints#
Checkpoint 1: At x=6, why do [2,6) and [6,8) not create overlap 2?
Answer: The first excludes 6 while the second includes it; their grouped delta is zero and active remains one.
Half-open semantics make ownership of the endpoint explicit, and grouping prevents a transient order-dependent count.
Checkpoint 2: Why is the gap length added before applying delta[x]?
Answer: active before x describes [previousX,x).
Events at x affect coverage beginning at x, not the segment that ends there. Reversing the order attributes the preceding gap to the wrong state.
Guided exercises
- Given room reservations under [start,end), return only the peak number of simultaneous rooms required.
Checkpoint: Use the same grouped deltas and update peak after applying each coordinate's net delta; union-length accumulation is unnecessary. - Given painted integer segments, return only their total union length.
Checkpoint: Add each coordinate gap when active>0; a peak variable is unnecessary because it answers a different query.
Practice and transfer#
Unseen variant: Return every maximal half-open segment on which the active count is at least two, merging adjacent qualifying gaps.
Checkpoint: The pre-event active state labels [previousX,x); append or extend that gap when active≥2, then apply the grouped delta at x.
Practice handoffs
- Practice capacity eventsUse ordered deltas to enforce a capacity invariant.
- Compare interval mergingChoose a direct sorted scan when the output is merged intervals rather than event-state aggregates.
Follow-up constraints
- How would closed intervals change the equal-coordinate event contract?
- Return the first coordinate at which capacity is exceeded without computing union length.
- Explain when coordinate compression plus a difference array is preferable to an ordered map.
Sources and review#
This original Engineering Foundry lesson received Codex self-review on 2026-09-05; independent human editorial review is not claimed.
- Length of the union of segments (opens in a new tab) - Sorted endpoint sweeping for covered length; the combined grouped-delta contract is independently authored for this lesson.
- MIT 6.006 Introduction to Algorithms lecture notes (opens in a new tab) - Academic cross-check for sorting and algorithmic complexity, not an interview-frequency claim.