ExamAdda Logo

Merge Overlapping Intervals

Medium

Given an array of intervals where intervals[i] = [start, end], merge all overlapping intervals and return an array of non-overlapping intervals that cover all the original intervals.

Two intervals overlap if they share at least one point, including their endpoints.

Example 1

Input

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

Output

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

Explanation

[1,3] and [2,6] overlap, so they merge into [1,6]. The other intervals remain separate.

Example 2

Input

intervals = [[1,4],[4,5]]

Output

[[1,5]]

Explanation

Both intervals share the endpoint 4, so they merge into [1,5].

Constraints

1 <= intervals.length <= 10^4
intervals[i].length == 2
0 <= start <= end <= 10^4

Hints:

Hint 1

Sort the intervals by their starting points.

Hint 2

Compare each interval with the last merged interval. If they overlap, extend the last interval's ending point; otherwise, add a new interval.

Author & Technical Reviewer

Chatla Jithin Sri Surya

Written by: Chatla Jithin Sri Surya

Chatla Jithin Sri Surya

Technically reviewed by: Chatla Jithin Sri Surya

Published

Oct 27, 2026

Last updated

Oct 27, 2026

Last technically reviewed

Oct 27, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output