Skip to main content

Unified Span Combiner

easy
IntervalsArraySortingGreedy IntervalIntervals Merge
Asked atGoogleAmazonMicrosoftMetaBloomberg

Problem Description

You are given a list of intervals where each interval is represented as `[start, end]` (inclusive). Merge all overlapping or adjacent intervals and return the resulting list of non-overlapping intervals sorted by start time.

Two intervals `[a, b]` and `[c, d]` overlap if `c <= b + 1` when sorted, i.e. they share at least one point or are adjacent.

**Example 1:**
```
Input: spans = [[3,7],[1,4],[8,10],[2,6]]
Output: [[1,7],[8,10]]
```

**Example 2:**
```
Input: spans = [[5,9],[1,2],[3,5],[10,14],[12,16]]
Output: [[1,2],[3,9],[10,16]]
```

Constraints

  • 1 <= spans.length <= 10^4
  • 0 <= spans[i][0] <= spans[i][1] <= 10^6

Follow-up

Can you solve this problem in-place without allocating a new list? What is the minimum number of intervals that must be removed to make the remaining intervals non-overlapping?

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.