We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A medium intervals problem, graded against 6 test cases (3 of them hidden).
Sorting by start or end, then merging or scheduling overlapping ranges.
Reach for it when you see: Meetings, bookings, ranges, or anything with a start and an end.
More Intervalsproblems →Because the input is sorted and non-overlapping, the intervals split cleanly into three consecutive groups, and you can handle each in order:
1. Strictly before - `interval.end < newInterval.start`. These can never touch the new interval; copy them out unchanged.
2. Overlapping - everything with `interval.start <= newInterval.end`. Rather than emitting these, absorb them: widen the new interval to `min(starts)` and `max(ends)`. When the loop ends, push the widened interval exactly once.
3. Strictly after - copy the remainder unchanged.
The comparisons are where this goes wrong. Both boundary tests use non-strict logic against the *other* endpoint, so intervals that merely touch (`[1,3]` and `[3,5]`) merge rather than being emitted separately - matching the usual convention for this problem, and the opposite of the meeting-rooms convention. It is worth confirming which one the interviewer wants.
No sort is needed, so this beats the merge-intervals approach of appending and re-sorting.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.