Number of Intersecting Interval Pairs II Problem
Description
LeetCode Problem 4057.
You are given a 2D integer array intervals of n elements, where intervals[i] = [start_i, end_i] represents the closed interval from start_i to end_i.
Return the number of pairs of indices (i, j) such that 0 <= i < j < n and intervals[i] and intervals[j] intersect.
Two intervals intersect if they have at least one point in common, including when they only share an endpoint.
Example 1:
Input: intervals = [[1,2],[2,3],[3,4]]
Output: 2
Explanation:
There are 2 intersecting interval pairs:
- Intervals [1, 2] and [2, 3] intersect at the point 2.
- Intervals [2, 3] and [3, 4] intersect at the point 3.
Example 2:
Input: intervals = [[1,5],[2,4],[3,6]]
Output: 3
Explanation:
There are 3 intersecting interval pairs:
- The intersection of [1, 5] and [2, 4] is [2, 4].
- The intersection of [1, 5] and [3, 6] is [3, 5].
- The intersection of [2, 4] and [3, 6] is [3, 4].
Example 3:
Input: intervals = [[1,2],[3,4],[5,6]]
Output: 0
Explanation:
There are no intersecting interval pairs. Hence, the answer is 0.
Constraints:
2 <= n == intervals.length <= 10^5intervals[i] = [start_i, end_i]0 <= start_i <= end_i <= 10^9
Solution
Approach: Count the Disjoint Pairs
It is easier to count pairs that do not intersect and subtract them from the total n(n-1)/2.
Two intervals are disjoint exactly when one ends before the other starts. Each disjoint pair has a unique "left" interval (the one that ends first) and a "right" interval (the one that starts later), so we can count it from the right interval's side: the number of intervals whose end is strictly less than its start.
Sort all starts and all ends separately. Walk through the starts in increasing order, and keep a pointer i to the number of ends that are smaller than the current start. The pointer only moves forward because the starts are increasing. Subtract i from the total for each start.
The total can be as large as about 5 * 10^9, so use a 64-bit integer.
Complexity: O(n log n) time for the two sorts and O(n) extra space.
class Solution:
def countIntersectingIntervals(self, intervals: List[List[int]]) -> int:
n = len(intervals)
starts = sorted(s for s, _ in intervals)
ends = sorted(e for _, e in intervals)
ans = n * (n - 1) // 2
i = 0
for start in starts:
while i < n and ends[i] < start:
i += 1
ans -= i
return ans