Data Structures & Algorithms Sorting Algorithms
💡
Exercise 60

Merge Intervals 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Given an array of intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals and return the non-overlapping intervals.

intervals = [[1,3],[2,6],[8,10],[15,18]] # [1,3] and [2,6] overlap → merge to [1,6] # Output: [[1,6],[8,10],[15,18]]

Algorithm:

  • Sort intervals by start time
  • Initialize result with first interval
  • For each next interval: if it overlaps with last in result (start ≤ last end), merge by extending the end
  • Otherwise, add as new non-overlapping interval

Time: O(n log n) for sorting. Space: O(n) for result.

📋 Instructions
Implement `merge_intervals(intervals)` that merges overlapping intervals. Test with `[[1,3],[2,6],[8,10],[15,18]]`. Print the result.
Sort by start. Use a result list. For each interval, compare its start with the end of the last interval in result. If overlapping, update the end to max of both ends. Otherwise append.
🧪 Test Cases
Input
merge_intervals([[1,3],[2,6],[8,10],[15,18]])
Expected
[[1, 6], [8, 10], [15, 18]]
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.