Katkat

Merge Overlapping Intervals

J.P. MorganSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to manipulate array-based data by identifying and merging intersecting ranges using a greedy sorting strategy.

Merge Overlapping Intervals

You are given an array of intervals where each interval is defined as [start, end]. Write a function merge_intervals(intervals) that merges all overlapping intervals and returns an array of the non-overlapping intervals that cover all the intervals in the input.

Two intervals [a, b] and [c, d] overlap if there is any point that lies in both intervals (e.g., [1, 3] and [2, 4] overlap).

Function Signature

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

Constraints

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

Examples

Example 1: Input: intervals = [[1, 3], [2, 6], [8, 10], [15, 18]] Output: [[1, 6], [8, 10], [15, 18]] Explanation: Since [1, 3] and [2, 6] overlap, merge them into [1, 6].

Example 2: Input: intervals = [[1, 4], [4, 5]] Output: [[1, 5]] Explanation: Intervals that share a boundary point are considered overlapping.

Edge Cases

  • Empty input list.
  • A single interval.
  • Intervals fully contained within another (e.g., [[1, 10], [2, 5]]).
  • Intervals already sorted or completely unsorted.

Hints

Hint 1

Consider sorting the intervals based on their start times first to simplify the comparison process.

Hint 2

Once sorted, an interval can be merged with the previous one if its start time is less than or equal to the previous interval's end time.

Hint 3

Maintain a result list and compare the current interval with the last interval added to the list to determine if you should merge or append.

Follow-up questions

  • What is the time and space complexity of your solution, and can you optimize it?
  • How would you modify your approach if the input was a massive stream of intervals rather than a static list?
  • If the input was guaranteed to be sorted by start time, how would the complexity change?