Katkat

Merge overlapping intervals

AtlassianSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to manipulate array-based data structures, specifically focusing on sorting and linear-time interval merging logic.

Problem Statement

Given a collection of intervals, merge all overlapping intervals and return an array of the non-overlapping intervals that cover all the intervals in the input.

An interval is defined as [start, end]. Two intervals [a, b] and [c, d] overlap if c List[List[int]]:

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, merge them into [1, 6].

Example 2: Input: [[1, 4], [4, 5]] Output: [[1, 5]] Explanation: Intervals [1, 4] and [4, 5] are considered overlapping because they touch at 4.

Constraints

  • 1 <= intervals.length <= 10^4
  • 0 <= start_i <= end_i <= 10^4

Edge Cases to Consider

  • Empty input list.
  • A list containing a single interval.
  • Intervals that are completely nested inside others (e.g., [[1, 10], [2, 3]]).
  • Intervals that are identical.

Hints

Hint 1

Consider sorting the intervals based on their start times first; how does this simplify the merging process?

Hint 2

If you sort the list, can you determine if two intervals overlap by comparing the end of the current merged interval with the start of the next one?

Hint 3

Use a result list to store merged intervals and compare the latest interval in the list with the next interval from the sorted input.

Follow-up questions

  • What is the time and space complexity of your solution, and can you optimize the space complexity?
  • How would your approach change if the input intervals were not contiguous integers but represented timestamps, and you needed to handle a very large number of intervals stored on disk?
  • What if the input intervals were already sorted by their start times—could you improve the runtime complexity?