Menu
CoddyTech

Merge Intervals

You get a set of intervals, each a range of whole numbers from a start to an end. Merge every group of overlapping intervals into one interval that covers the whole group, and return the merged intervals sorted by start. Intervals that only touch, like [1, 4] and [4, 5], count as overlapping.

The intervals come in as two arrays of the same length: interval i is [starts[i], ends[i]]. You return a 2D array, a list of [start, end] pairs.

Function

mergeIntervals(starts: integer-array, ends: integer-array) → integer-2d-array
startsinteger-array
the start of each interval
endsinteger-array
the end of each interval, at the same index as its start
Returnsinteger-2d-array
the merged intervals as [start, end] pairs, sorted by start

Constraints

  • 1 ≤ starts.length == ends.length ≤ 104
  • 0 ≤ starts[i] ≤ ends[i] ≤ 104
  • The intervals arrive in any order.
  • Intervals that only touch at an end count as overlapping.

Examples

Input
starts = [5, 1, 12, 3]ends = [7, 4, 14, 6]
Output
[[1, 7], [12, 14]]
Explanation
In order of start, [1, 4] overlaps [3, 6], which overlaps [5, 7], so the three become [1, 7]. [12, 14] starts after 7 and stays on its own.
challenge icon

Follow-up

The intervals arrive already merged and sorted by start, and you must add one new interval. Can you return the merged list in O(n) time, without sorting again?

Reset code
def mergeIntervals(starts, ends):
    # Write code here

Test #1

Test #2

Arguments

starts = [5, 1, 12, 3]
ends = [7, 4, 14, 6]

Expected Output

[[1, 7], [12, 14]]