Intervals & Sweep Lines Hard
Interval Union Sweep
Sort closed intervals by their lower endpoint, then scan once: overlapping or endpoint-touching intervals extend the current range; a strict gap closes it.
Trace input
Bounded JSONEdit the lesson input, then build a deterministic source-linked trace.
Source scenarios
Complexity
BestO(N log N)
AverageO(N log N)
WorstO(N log N)
SpaceO(N) for the result list
Array state
Follow the active comparisons and writes.
Current operation
Trace stateReady to explore
Source behavior & common mistakes
Follow the source comparator, sort, and sweep. Produce the minimal ascending set of closed intervals with exactly the same coverage as the input.
- Intervals are closed: [1,2] and [2,4] overlap at 2 and merge; [1,2] and [3,4] remain separate.
- A new result is emitted only when next.min > current max; equality is still merged.
- The source sorts its input array in place, while this lesson models that sorted working array without mutating the caller's input object.
- Interval.compareTo returns max - other.max when mins tie. Java int overflow can make this comparator inconsistent at extreme endpoints; the trace reproduces its 32-bit result, and the Java oracle checks the resulting union.
- Empty input returns the original empty array immediately and performs no sort or interval allocation.
Algorithm code
JavaUnion.javaStep linked
The highlighted line follows the current step.
Ready to begin
Press Play to see what happens.
Detailed execution
Snapshot 1 / 1