Greedy · Medium
A reporting service receives possibly overlapping periods and must calculate the total time covered at least once. Summing individual durations double-counts overlaps, while counting requests measures a different quantity. Imported endpoints can be reversed and need a clear normalization rule.
Return the numeric length of the union of all retained intervals without counting any covered segment more than once.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ intervals: [integer, integer][], closed: boolean }
Fields
- Each interval is an unordered endpoint pair [a,b]. Normalize it to start=min(a,b), end=max(a,b); input order is arbitrary.
- closed=true means [start,end], including both endpoints. closed=false means [start,end), excluding end. Ignore zero-length half-open ranges entirely; a zero-length closed range is one point.
Output
Return value
- Return a non-negative integer length in the same units as the endpoints.
- Closed point windows have zero length. Endpoint inclusion does not change numeric union length, and empty input returns zero.
Constraints
- 0 <= intervals.length <= 100000. Endpoints are integers from -1000000000 to 1000000000.
- closed is always a boolean. Do not mutate the input or its nested pairs. Duplicate intervals remain separate requests unless the objective merges coverage.
Examples
Example 1
{
"closed": true,
"intervals": [
[
0,
4
],
[
2,
6
]
]
}Returns
6Example 2
{
"closed": false,
"intervals": [
[
3,
3
],
[
9,
7
]
]
}Returns
2Required complexity
O(n log(n + 1)) time and O(n) auxiliary space