learn deep. ship safe.Practice testsFollow ByteMunSubscribe

mediumArraysSortingIntervals

Merge Overlapping Intervals

Merge a list of time ranges so that no two overlap. A practical problem behind calendars and booking systems, and a favourite for testing sorting logic.

By Tests checked by DeepakJavaScript or Python

Given a list of intervals [start, end] (with start <= end), merge all intervals that overlap and return the merged list sorted by start.

Intervals that only touch, such as [1, 3] and [3, 5], count as overlapping.

Examples

Example 1

Input: intervals = [[1, 3], [8, 10], [2, 6], [15, 18]]
Output: [[1, 6], [8, 10], [15, 18]]
Why: [1, 3] and [2, 6] overlap

Example 2

Input: intervals = [[1, 4], [4, 5]]
Output: [[1, 5]]
Why: Touching intervals merge

Constraints

  • 1 <= intervals.length <= 10^4
  • 0 <= start <= end <= 10^4

Hints

Hint 1

Overlaps are easy to spot if the intervals are in order. In which order?

Hint 2

After sorting by start, compare each interval with the last merged one: extend it, or start a new one.

Solution

Show the solution (try it yourself first)

Approach: sort, then sweep

Sort the intervals by their start. Then any interval that overlaps the previous merged block must start at or before that block's end. Walk through the sorted list: if the current interval starts at or before the end of the last merged interval, extend that end to the larger of the two ends; otherwise start a new block. Taking the maximum matters when one interval swallows the next, as in [1, 10] followed by [2, 3]. Copy the input before sorting if the caller's list must not change.

def merge_intervals(intervals):
    out = []
    for s, e in sorted(intervals):
        if out and s <= out[-1][1]:
            out[-1][1] = max(out[-1][1], e)
        else:
            out.append([s, e])
    return out

Complexity

Time O(n log n) for the sort; the sweep is O(n). Space O(n) for the output. Follow-up: inserting one new interval into an already merged, sorted list can be done in O(n) without re-sorting.

Case 1Input: [[1,3],[8,10],[2,6],[15,18]]Expected: [[1,6],[8,10],[15,18]]
Case 2Input: [[1,4],[4,5]]Expected: [[1,5]]

Run checks these 2 samples. Submit checks all 7 tests, including hidden ones.

  1. Maximum Subarray SumArrays · Dynamic programming
    medium
  2. Group AnagramsStrings · Hash map · Sorting
    medium
  3. Pair with Target SumArrays · Hash map
    easy
  4. Search a Sorted ArrayBinary search · Arrays
    easy