Greedy · Medium
A timeline groups imported windows when overlap connects them directly or through other windows. It needs a group count rather than a room count or a chosen schedule. Touching half-open windows remain separate groups unless a third window overlaps and connects both.
Return the number of connected groups formed by overlap among the retained intervals.
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 one integer number of overlap-connected groups; empty input returns zero.
- Overlapping chains belong to one group even if their first and last windows do not directly overlap. Touching alone connects closed windows but not half-open windows.
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,
3
],
[
2,
5
],
[
4,
7
]
]
}Returns
1Example 2
{
"closed": false,
"intervals": [
[
0,
1
],
[
1,
2
]
]
}Returns
2Required complexity
O(n log(n + 1)) time and O(n) auxiliary space