Intervals Merging and scheduling

506. Merge Intervals

Medium 147 DSA Sheet

You are given an array intervals, where intervals[i] = [start, end] covers every number from start to end, both included. The intervals come in any order.

Merge each group of overlapping intervals into one interval that covers the whole group. Return the merged intervals sorted by start.

Two intervals overlap when they share at least one point. So [1,3] and [3,5] overlap and merge into [1,5], while [1,2] and [3,4] share no point and stay apart.

Example 1

Input: intervals = [[4, 7], [1, 3], [11, 12], [2, 5], [9, 10]]

Output: [[1,7],[9,10],[11,12]]

Explanation: [1,3] and [2,5] overlap, and [4,7] overlaps both of them, so the three merge into [1,7]. The other two intervals overlap nothing and stay as they are.

Example 2

Input: intervals = [[5, 8], [1, 5]]

Output: [[1,8]]

Explanation: The two intervals share the point 5, so they merge.

Example 3

Input: intervals = [[-10, 10], [-3, -1], [0, 0]]

Output: [[-10,10]]

Explanation: The other two intervals lie inside [-10,10]. [0,0] is a single point.

Check your understanding

Work out the answer for this input before you write any code.

intervals = [[1, 10], [2, 3], [4, 5], [12, 14]]

Constraints

  • 1 ≤ intervals.length ≤ 105
  • intervals[i].length = 2
  • -109 ≤ start ≤ end ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.