Count Ways to Group Overlapping Ranges Problem
Description
LeetCode Problem 2580.
You are given a 2D integer array ranges where ranges[i] = [start_i, end_i] denotes that all integers between start_i and end_i (both inclusive) are contained in the i^th range.
You are to split ranges into two (possibly empty) groups such that:
- Each range belongs to exactly one group.
- Any two overlapping ranges must belong to the same group.
Two ranges are said to be overlapping if there exists at least one integer that is present in both ranges.
- For example,
[1, 3]and[2, 5]are overlapping because2and3occur in both ranges.
Return the total number of ways to split ranges into two groups. Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: ranges = [[6,10],[5,15]]
Output: 2
Explanation:
The two ranges are overlapping, so they must be in the same group.
Thus, there are two possible ways:
- Put both the ranges together in group 1.
- Put both the ranges together in group 2.
Example 2:
Input: ranges = [[1,3],[10,20],[2,5],[4,8]]
Output: 4
Explanation:
Ranges [1,3], and [2,5] are overlapping. So, they must be in the same group.
Again, ranges [2,5] and [4,8] are also overlapping. So, they must also be in the same group.
Thus, there are four possible ways to group them:
- All the ranges in group 1.
- All the ranges in group 2.
- Ranges [1,3], [2,5], and [4,8] in group 1 and [10,20] in group 2.
- Ranges [1,3], [2,5], and [4,8] in group 2 and [10,20] in group 1.
Constraints:
1 <= ranges.length <= 10^5ranges[i].length == 20 <= start_i <= end_i <= 10^9
Solution
Approach: Sorting + Counting
Overlapping ranges must end up in the same group, so first sort the ranges by start and merge the overlapping ones. Let cnt be the number of merged blocks that remain.
Each block can go to either of the two groups independently, which gives 2^cnt ways, taken modulo 10^9 + 7. Instead of fast power, we can simply multiply the answer by 2 (mod 10^9 + 7) each time a new non-overlapping block starts, that is, when the start is greater than the largest end seen so far.
The time complexity is O(n log n) and the space complexity is O(log n), where n is the number of ranges.
class Solution:
def countWays(self, ranges: List[List[int]]) -> int:
ranges.sort()
cnt, mx = 0, -1
for start, end in ranges:
if start > mx:
cnt += 1
mx = max(mx, end)
mod = 10**9 + 7
return pow(2, cnt, mod)