DSAVisualiseData Structures & Algorithms Studio
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 JSON

Edit the lesson input, then build a deterministic source-linked trace.

This lesson validates its own input and operation limits.

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.

Live snapshot

Current operation

Trace state
Ready 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

Java
Union.javaStep linked
The highlighted line follows the current step.

Ready to begin

Press Play to see what happens.

Detailed execution
Snapshot 1 / 1