Intervals · Medium
A scheduling screen receives overlapping busy intervals from several calendars. The UI needs a compact timeline.
Merge overlapping or touching half-open intervals and return them in chronological order.
Input
Call
- Implement
solve(input)and return its result. Do not print fromsolve.
Input object
{ slots: [start: integer, end: integer][] }
Input rules
- Every interval satisfies start < end.
What each field means
slots— an unsorted array of[start, end]time intervals. Each interval starts before it ends.
Output
Return value and rules
- Return merged
[start, end]intervals ordered by start time. - Merge intervals that overlap or touch:
[1, 3]and[3, 6]become[1, 6]. - Return
[]for no slots. Do not change the input array.
Constraints
- 0 <= slots.length <= 100000
- -1000000000 <= start < end <= 1000000000
- Input is not sorted; do not mutate it.
Examples
Example 1
{
"slots": [
[
5,
9
],
[
1,
3
],
[
3,
6
]
]
}Returns
[
[
1,
9
]
]Example 2
{
"slots": []
}Returns
[]Required complexity
O(n log n) time and O(n) output space