Intervals · Medium
A reporting service receives coverage ranges from several workers. The ranges can arrive out of order and overlap. It needs a minimal ordered list describing the same covered coordinates before drawing the result.
Merge overlapping or touching closed intervals and return disjoint ranges in ascending start order.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "intervals": [number, number][] } where each pair is [start, end].
Fields
- intervals is an array of [start,end] integer pairs. Each pair includes both endpoints and satisfies start <= end.
Output
Return value
- Return an array of [start,end] pairs without changing the original pairs.
- Ranges sharing an endpoint merge: [1,2] and [2,3] become [1,3].
- A gap does not merge: [1,2] and [3,4] remain separate.
- Duplicate and contained ranges do not create extra output. Empty input returns [].
Constraints
- 0 <= intervals.length <= 100000.
- Endpoints are integers in [-1000000000,1000000000].
- Zero-length ranges such as [4,4] are valid closed intervals.
Examples
Example 1
{
"intervals": [
[
5,
7
],
[
1,
2
],
[
2,
6
]
]
}Returns
[
[
1,
7
]
]Touching ranges connect the full chain.
Example 2
{
"intervals": [
[
1,
2
],
[
3,
4
]
]
}Returns
[
[
1,
2
],
[
3,
4
]
]The gap between 2 and 3 is not covered.
Required complexity
O(n log(n + 1)) time and O(n) space including the copied input and output