CodeArchon

mediumIntervalsFacebookGoogle

Overlap Collapser

A calendar app collapses any overlapping meetings into single union intervals.

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

Choose approach

1/5
Narrationstep 1 of 5

I0 starts a new output interval.

1def merge(intervals):
2 intervals.sort(key=lambda x: x[0])
3 res = []
4 for s, e in intervals:
5 if res and res[-1][1] >= s:
6 res[-1][1] = max(res[-1][1], e)
7 else:
8 res.append([s, e])
9 return res
Variables
i=0
start=1
end=3

How to think about it

  1. Sorting makes overlap-detection local.
  2. Compare current with the last output only.

Edge cases to catch in interview

  • Empty -> [].
  • All disjoint -> same as input (sorted).

Examples

Example 1[[1,5]]
{"intervals":[[1,4],[4,5]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed