⌘K
Flycodx

Merge Intervals

Merge Intervals

MediumSorting20% accepted

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

4 1 3 2 6 8 10 15 18

Output

[[1,6],[8,10],[15,18]]
  • •1 ≤ n ≤ 10^4, 0 ≤ start_i ≤ end_i ≤ 10^4
solution.py
Loading editor...
Test 1
Test 2
Test 3

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
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3