Merge Intervals
Merge Intervals
Given an array of intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals and return the resulting list of non-overlapping intervals. Two intervals [a, b] and [c, d] overlap if c ≤ b (the second starts before or when the first ends). Example: intervals=[[1,3],[2,6],[8,10],[15,18]] → [[1,6],[8,10],[15,18]]
Input format — only if your code reads from stdin
Input format: - First line: integer n (number of intervals) - Next n lines: two integers start end per interval Output: the merged intervals, one per line (start end).
Approach
Sort intervals by start time. Initialize the result with the first interval. For each subsequent interval, if its start ≤ current result's end (overlap), merge by extending the end to max(current.end, new.end). Otherwise, add as a new interval.
Input
Output
- •
1 ≤ n ≤ 10^4, 0 ≤ start_i ≤ end_i ≤ 10^4
More Sorting problems
Browse all coding problems →Press Run to test your custom input, or Submit to judge against all test cases.
Sign in to continue
Create a free account to run code, submit solutions and track progress.
- Free forever — no credit card
- 10+ languages with live execution
- Points, streaks & leaderboards