ExamAdda Logo

Merge Intervals

Easy

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals and return an array of the non-overlapping intervals that cover all the intervals in the input.

Example 1

Input

4
1 3
2 6
8 10
15 18

Output

"1 6\n8 10\n15 18"

Explanation

Generated from the visible test case.

Example 2

Input

5
1 4
4 5
6 8
7 9
10 12

Output

"1 5\n6 9\n10 12"

Explanation

Generated from the visible test case.

Example 3

Input

1
1 4

Output

"1 4"

Explanation

Generated from the visible test case.

Example 4

Input

3
1 4
5 6
7 8

Output

"1 4\n5 6\n7 8"

Explanation

Generated from the visible test case.

Constraints

1 ≤ intervals.length ≤ 10⁴
intervals[i].length == 2
0 ≤ starti ≤ endi ≤ 10⁴

Hints:

Hint 1

Sort the intervals based on their starting time.

Hint 2

Traverse the sorted intervals. If the current interval overlaps with the last merged interval, merge them; otherwise, add it as a new interval.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 6, 2026

Last updated

Aug 9, 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