Merge Intervals

35 min · merge()

A calendar export can describe one busy stretch with several overlapping blocks. Before you show it to a person, those fragments need to become one clean range.

Given an array intervals, where every entry is [start, end], combine all overlapping intervals. Return the combined intervals sorted by ascending start.

Treat intervals as closed ranges: two intervals overlap when they share even one endpoint. For example, [1, 4] and [4, 5] combine into [1, 5].

A few ground rules:

  • start is always less than or equal to end.
  • The input may arrive in any order and may contain duplicate intervals.
  • Every covered point must appear in exactly one returned interval.

Constraints

  • 1 <= intervals.length <= 100_000
  • Every interval has exactly two integers: [start, end].
  • 0 <= start <= end <= 1_000_000_000

Hints

Find an ordering that helps

If intervals are sorted by start, any range that can extend the current merged range appears before a range that starts beyond it.

Keep one active range

Compare the next interval's start with the active range's end. If the start is no greater, extend the end when needed. Otherwise, the active range is finished.

Touching still counts

The overlap check is next_start <= current_end, not a strict comparison. Equality means the intervals share an endpoint and must merge.

Follow-up

Could you describe which part of the algorithm proves that a finished interval can never overlap anything you haven't scanned yet?

Visible cases

Examples

Example 1

ready
Input
intervals = [
  [
    1,
    3
  ],
  [
    2,
    6
  ],
  [
    8,
    10
  ],
  [
    15,
    18
  ]
]
Expected
[
  [
    1,
    6
  ],
  [
    8,
    10
  ],
  [
    15,
    18
  ]
]
Why
the first two ranges overlap; the later two stay separate

Example 2

ready
Input
intervals = [
  [
    1,
    4
  ],
  [
    4,
    5
  ]
]
Expected
[
  [
    1,
    5
  ]
]
Why
sharing endpoint 4 makes the two closed ranges overlap

Example 3

ready
Input
intervals = [
  [
    5,
    7
  ],
  [
    1,
    2
  ],
  [
    2,
    4
  ]
]
Expected
[
  [
    1,
    4
  ],
  [
    5,
    7
  ]
]
Why
sorting exposes the touching chain from 1 through 4

Interview signal

Asked at

AmazonGoogleMetaBloomberg
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite