Dataford
Interview Guides
Upgrade
All questions/Coding/Merge Intervals for Overlapping Events

Merge Intervals for Overlapping Events

Medium
Coding
Dynamic Programming

Problem

Problem

Given a list of intervals, each represented as a pair of integers [start, end], merge all overlapping intervals and return a new list of non-overlapping intervals. Each interval is inclusive of its start and end times.

Examples

Example 1:

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

Example 2:

Input: intervals = [[1, 4], [4, 5]]
Output: [[1, 5]]

Constraints

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

Examples

Example 1
Inputintervals = [[1, 3], [2, 6], [8, 10], [15, 18]]Output[[1, 6], [8, 10], [15, 18]]WhyThe intervals [1, 3] and [2, 6] overlap, so they are merged into [1, 6]. The others do not overlap.
Example 2
Inputintervals = [[1, 4], [4, 5]]Output[[1, 5]]WhyThe intervals [1, 4] and [4, 5] touch at 4, thus they are merged into [1, 5].

Constraints

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

Function Signature

def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:

Problem

Problem

Given a list of intervals, each represented as a pair of integers [start, end], merge all overlapping intervals and return a new list of non-overlapping intervals. Each interval is inclusive of its start and end times.

Examples

Example 1:

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

Example 2:

Input: intervals = [[1, 4], [4, 5]]
Output: [[1, 5]]

Constraints

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

Examples

Example 1
Inputintervals = [[1, 3], [2, 6], [8, 10], [15, 18]]Output[[1, 6], [8, 10], [15, 18]]WhyThe intervals [1, 3] and [2, 6] overlap, so they are merged into [1, 6]. The others do not overlap.
Example 2
Inputintervals = [[1, 4], [4, 5]]Output[[1, 5]]WhyThe intervals [1, 4] and [4, 5] touch at 4, thus they are merged into [1, 5].

Constraints

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

Function Signature

def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:
Practice Python
Python 3.10
Open on desktop for the full Python editor with syntax highlighting and autocomplete.
Up next
TwitchMerge Overlapping IntervalsMediumWalmartMerge Overlapping Time IntervalsMediumMetaMerge Overlapping Time IntervalsMedium
Next question