AlgoPrecision

Greedy

Local Choice Visualizer

Watch greedy strategies sort, scan, select, merge, and reset state while each step updates the current result and complexity.

O(n log n) time / O(n) space
result: -selected: 0
I1default

[1, 3]

start 1 / end 3

I2default

[2, 6]

start 2 / end 6

I3default

[8, 10]

start 8 / end 10

I4default

[9, 12]

start 9 / end 12

Result

-

Time

O(n log n)

Space

O(n)

Step Note

Sort intervals by start time.

Details
function mergeIntervals(intervals: Interval[]) {
  intervals.sort((a, b) => a.start - b.start)
  const merged = []
  for (const interval of intervals) {
    const last = merged.at(-1)
    if (!last || interval.start > last.end) merged.push(interval)
    else last.end = Math.max(last.end, interval.end)
  }
  return merged
}