Solvarch
DSA ProblemsProgressPlanRoadmapsReviewCheat SheetsCompaniesSystem DesignCS FundamentalsQuestion Bank
Theme
Problems

Merge Intervals

Medium
arrayintervalssorting

Given a list of intervals [start, end], merge all overlapping intervals and return the result sorted by start.

Input

  • Line 1: two integers n 2 (n intervals)
  • Next n lines: start end

Output: the merged intervals, one per line as start end.

Example 1
Input:
4 2
1 3
2 6
8 10
15 18
Output:
1 6
8 10
15 18

[1,3] and [2,6] overlap → [1,6].

Example 2
Input:
2 2
1 4
4 5
Output:
1 5

Touching endpoints merge.

Constraints

  • 1 ≤ n ≤ 10^4
  • 0 ≤ start ≤ end ≤ 10^4
Watch a video walkthrough

Run your code against the sample tests, or Submit to run the full suite.