KatInterview

Combine Overlapping Intervals

Greedy & IntervalsAuto-graded · 24 test cases
MediumAuto-gradedGreedy & Intervalsintervalssortingarrays

Last updated

Tests interval merging through sorting and linear scanning, focusing on edge-case handling for touching and nested ranges.

Combine Overlapping Intervals

You receive a collection of intervals, each represented as a pair of integers [start, end]. Two intervals are considered overlapping if they share at least one point in common, including their boundaries. For instance, [1, 3] and [3, 5] overlap at point 3 and should combine into [1, 5].

Write a function that processes a list of such intervals and produces a new list where all overlapping intervals have been consolidated into single continuous ranges.

Constraints

  • 1 <= intervals.length <= 10,000
  • 0 <= start < end <= 10^9
  • Each interval [start, end] satisfies start < end

Notes

  • Intervals that touch at endpoints must be merged
  • An interval completely inside another should be absorbed
  • The input may arrive in any order

Examples

Example 1

Input: combine_intervals([[1, 3], [2, 6], [8, 10], [15, 18]])

Output: [[1, 6], [8, 10], [15, 18]]

Example 2

Input: combine_intervals([[1, 4], [4, 5]])

Output: [[1, 5]]

Hints

Hint 1

Consider how sorting the intervals by their starting points simplifies overlap detection

Hint 2

When intervals are sorted, you only need to check if each new interval overlaps with the most recently merged range

Hint 3

Remember that intervals touching at a single point (like [1,4] and [4,5]) count as overlapping