1. Understand the problem

Given an array of intervals, merge all overlapping intervals and return the intervals that remain.

Each interval is represented as:

[start, end]

Example:

intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]

Visualize the intervals:

Interval [1, 3]:   1 ─── 3
Interval [2, 6]:       2 ─────── 6
Interval [8, 10]:                     8 ─── 10
Interval [15, 18]:                                15 ───── 18

The first two intervals overlap because [2, 6] starts before [1, 3] ends.

We merge them into [1, 6].

Output:

[[1, 6], [8, 10], [15, 18]]

The goal is to combine overlapping intervals while keeping non-overlapping intervals separate

2. Key idea (Signal)

The key signal is overlapping intervals.

The most useful observation is:

If we sort the intervals by their start time, we only need to compare each interval with the last merged interval.

For example, sort these intervals:

intervals = [[2, 6], [1, 3], [8, 10], [15, 18]]

After sorting by start time: