Katkat

Merge Overlapping Time Ranges

AmazonApplied Scientist · Technical Screen

Last updated

This problem tests your ability to manipulate arrays of intervals by sorting and merging, evaluating your proficiency with pointer manipulation and interval arithmetic.

Merge Overlapping Time Ranges

You are given a list of time intervals, where each interval is represented as a list of two integers [start, end]. An interval [a, b] overlaps with [c, d] if there is any common point between them, including endpoints (e.g., [1, 3] and [3, 5] should be merged into [1, 5]).

Your task is to write a function that takes a list of intervals and returns a new list of intervals where all overlapping intervals have been merged into a single continuous range.

Function Signature

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

Constraints

  • 1 <= intervals.length <= 10,000
  • 0 <= start < end <= 10^9

Examples

Example 1: Input: [[1, 3], [2, 6], [8, 10], [15, 18]] Output: [[1, 6], [8, 10], [15, 18]] Explanation: Since [1, 3] and [2, 6] overlap, they are merged into [1, 6].

Example 2: Input: [[1, 4], [4, 5]] Output: [[1, 5]] Explanation: Since the end of the first interval matches the start of the second, they are merged.

Edge Cases

  • A list containing a single interval.
  • Intervals that are completely contained within others (e.g., [[1, 10], [2, 5]]).
  • Unsorted input lists.

Hints

Hint 1

Consider sorting the intervals based on their start times first, as this allows you to process intervals in a linear sequence.

Hint 2

Maintain a result list and compare the current interval with the last interval added to the result list.

Hint 3

If the current interval's start time is less than or equal to the last interval's end time, they overlap; otherwise, the current interval is disjoint.

Follow-up questions

  • How would you modify your algorithm if the input list was already sorted by start time?
  • What is the time and space complexity of your solution, and can you optimize the space complexity?
  • How would you handle the case where the input contains invalid intervals (e.g., `start > end`)?