Count Ways to Group Overlapping Ranges - Problem
You are given a 2D integer array ranges where ranges[i] = [starti, endi] denotes that all integers between starti and endi (both inclusive) are contained in the ith 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 because 2 and 3 occur 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 109 + 7.
Input & Output
Example 1 — Basic Overlapping Ranges
$
Input:
ranges = [[6,10],[5,15]]
›
Output:
2
💡 Note:
The two ranges [6,10] and [5,15] overlap (they share integers 6,7,8,9,10), so they must be in the same group. We can put both in group 1 or both in group 2, giving us 2 ways total.
Example 2 — Non-overlapping Ranges
$
Input:
ranges = [[1,3],[10,20],[2,5],[4,8]]
›
Output:
4
💡 Note:
After sorting: [1,3],[2,5],[4,8],[10,20]. Ranges [1,3],[2,5],[4,8] all overlap and form one component. Range [10,20] is separate. So we have 2 components, giving us 2² = 4 ways.
Example 3 — All Separate
$
Input:
ranges = [[1,2],[3,4],[5,6]]
›
Output:
8
💡 Note:
All three ranges are non-overlapping, so we have 3 independent components. Each can go to either group: 2³ = 8 ways total.
Constraints
- 1 ≤ ranges.length ≤ 104
- ranges[i].length == 2
- 0 ≤ starti ≤ endi ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of ranges where each range [start, end] represents integers from start to end
2
Process
Group overlapping ranges together, count independent components
3
Output
Number of ways to split into two groups = 2^(components)
Key Takeaway
🎯 Key Insight: Merge overlapping ranges into components, then each component independently chooses a group
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code