Start learning free

LESSON 372 OF 437 · GREEDY

Merge Intervals in C++

Practice O(n log n)

Given a vector of intervals where intervals[i] = [starti, endi], merge all overlapping intervals and return a vector of the intervals that remain, sorted by their start.

Two intervals overlap when they share at least one point. Intervals that only touch, like [1,4] and [4,5], share the point 4, so they overlap too and merge into [1,5].

 

Example 1:

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: [1,3] and [2,6] overlap, so they merge into [1,6]. The other two overlap nothing.

Example 2:

Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: The two intervals touch at 4, which counts as overlapping.

Example 3:

Input: intervals = [[6,8],[1,9],[2,4],[4,7]]
Output: [[1,9]]
Explanation: The input isn't sorted. [1,9] covers every other interval, so they all merge into it.

 

Constraints:

  • 1 <= intervals.length <= 105
  • 0 <= starti <= endi <= 106

Note:

Your algorithm should run in O(n log n) time, where n is the number of intervals.

STEP 1 OF 7
    Ctrl + Enter to check

    Merge Intervals in C++

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free