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
Count Ways to Group Overlapping Ranges INPUT ranges = [[6,10],[5,15]] Number Line 5 6 10 15 [6,10] [5,15] Overlap [6,10] overlaps [5,15] [6,10] [5,15] 2 ranges total ALGORITHM STEPS 1 Sort by start [[5,15],[6,10]] 2 Merge overlapping Check if ranges overlap 3 Count groups Both overlap: 1 group 4 Calculate ways 2^groups mod (10^9+7) Merge Process: [5,15] start=5, end=15 [6,10] 6 <= 15 (overlap!) Merged: 1 group FINAL RESULT Independent Groups: 1 Group 1 [5,15] + [6,10] (must be together) Calculation: ways = 2^1 = 2 Way 1: Group1 in Set A, Set B empty Way 2: Group1 in Set B, Set A empty Output: 2 Key Insight: 1. Overlapping ranges MUST be in the same group (merge them into components) 2. Each independent group can go to either Set A or Set B: 2 choices per group 3. Total ways = 2^(number of independent groups) mod (10^9 + 7) TutorialsPoint - Count Ways to Group Overlapping Ranges | Optimal Solution
Asked in
Google 15 Microsoft 12 Amazon 8
12.0K Views
Medium Frequency
~25 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen