1377. Overlapping Pair Count
A radio network has n broadcast slots. Slot i uses the half-open time range from starts[i] up to but not including starts[i] + lengths[i]. Two slots interfere when they share a stretch of time of positive length, so a slot that ends exactly when another begins does not interfere with it.
Return, as a 64-bit integer, the number of unordered pairs of distinct slots {i, j} that interfere. Identical slots interfere with each other, and a pair is counted once no matter the order. End times can exceed 32-bit range.
Count all n(n-1)/2 pairs and subtract the pairs that do not interfere: for each slot, count the slots whose end is at most its start, using sorted ends and a binary search. Target O(n log n) time and O(n) space.
Example 1
- Input:
- starts = [0,2,4], lengths = [3,3,1]
- Output:
- 2
- Explanation:
Slots are [0,3), [2,5), [4,5); the first two overlap on [2,3) and the last two on [4,5), the first and last do not, so 2.
Example 2
- Input:
- starts = [1,3], lengths = [2,2]
- Output:
- 0
- Explanation:
The first slot ends at 3 exactly when the second starts, so they do not interfere.
Example 3
- Input:
- starts = [5], lengths = [5]
- Output:
- 0
- Explanation:
One slot has no partner, so the count is 0.
Constraints
- 1 ≤ n ≤ 105, where n is the length of
starts - starts.length == lengths.length
- 0 ≤ starts[i] ≤ 109
- 1 ≤ lengths[i] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)