Neural Mastery
← Practice
Merge Overlapping Intervalsmedium

Merge Overlapping Intervals

medium Python for AI 15–20 min

NumPy allowed · plain Python earns 10 bonus points

Combine overlapping temporal and numerical ranges into a minimal set of disjoint contiguous intervals.

Related Skills

Task

Implement merge_intervals(intervals): given an array of intervals [start, end], merge all overlapping intervals and return a new array of non-overlapping intervals in ascending order.

Function Signature

merge_intervals(intervals: list[list[int]]) -> list[list[int]]

Examples

Example 1: Classic Overlapping Set
Input: intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
Output: [[1, 6], [8, 10], [15, 18]]
Example 2: Touching Boundary Intervals
Input: intervals = [[1, 4], [4, 5]]
Output: [[1, 5]]
Example 3: Fully Enclosed Intervals
Input: intervals = [[6, 8], [1, 9], [2, 4], [4, 7]]
Output: [[1, 9]]

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Intervals satisfy start <= end.
  • Runs in O(n log n) time due to sorting.
Python3Saved ✓
def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:
"""Merge all overlapping intervals in list intervals and return non-overlapping
intervals that cover all the intervals in the input."""
# Your implementation here
pass

Case 1: Classic Overlapping Set
Input: intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
Expected: [[1, 6], [8, 10], [15, 18]]
Case 2: Touching Boundary Intervals
Input: intervals = [[1, 4], [4, 5]]
Expected: [[1, 5]]
Case 3: Fully Enclosed Intervals
Input: intervals = [[6, 8], [1, 9], [2, 4], [4, 7]]
Expected: [[1, 9]]