Greedy · Medium
An inspector can choose checkpoints on a number line. Each required coverage interval must contain at least one chosen checkpoint. One checkpoint may satisfy several intervals, including intervals that only share an endpoint.
Return the minimum number of checkpoints needed to hit every closed interval at least once.
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][] }.
Fields
- intervals is an unsorted array of integer [start,end] pairs with start <= end.
Output
Return value
- Return an integer count, not checkpoint coordinates.
- Both endpoints are included. An empty input requires zero checkpoints.
Constraints
- At most 100000 intervals; endpoints are integers in [-1000000000,1000000000].
Examples
Example 1
{
"intervals": [
[
1,
2
],
[
2,
4
],
[
5,
7
]
]
}Returns
2Checkpoints 2 and 5 suffice.
Example 2
{
"intervals": [
[
1,
10
],
[
2,
3
],
[
4,
5
]
]
}Returns
2The enclosing interval does not merge incompatible inner requirements.
Required complexity
O(n log(n + 1)) time and O(n) space for a non-mutating sort