Beyond Big O

Merge overlapping intervals

Merge overlapping intervals

Medium

Solution guide

Reveal solution guide — spoilers

Approach

  1. Copy the intervals, including independent pair storage where needed, and sort the copy by start position. Do not sort or mutate the original outer array or its intervals.
  2. Maintain a current merged interval. If the next start is less than or equal to its end, extend that end to the maximum of the two ends.
  3. If the next start is greater than the current end, emit the current interval and start a new one. Emit the final interval after the scan; empty input returns an empty result.

Why it works

Sorting ensures every unseen interval starts no earlier than the next interval under consideration. Once a gap appears, no later interval can connect back to the completed current interval. Taking the maximum end preserves the entire union when an interval is nested. Equality merges because endpoints belong to closed intervals.

Complexity

O(n log n) time for sorting and O(n) extra space for the independent copy/output. The merge scan is O(n).

Edge cases to check

  • [1, 3] and [3, 5] merge, but [1, 2] and [3, 4] remain separate; do not add one to the end for integer adjacency.
  • Nested, duplicate and zero-length intervals must not shrink a previously extended end.
  • Unsorted input is valid; reversed endpoints are outside the contract and need no repair.
Editor options
Typing preferences

Saved in this browser.

Restoring local drafts…