Count Ways to Group Overlapping Ranges - Problem

Imagine you're a data analyst tasked with organizing overlapping time intervals into two separate groups. You have a collection of ranges where each range [start, end] represents a continuous interval of integers.

Your challenge is to split these ranges into exactly two groups (either group can be empty) following one crucial rule: any two ranges that overlap must be placed in the same group.

Two ranges are considered overlapping if they share at least one common integer. For example:

  • [1, 3] and [2, 5] overlap because they both contain 2 and 3
  • [1, 2] and [3, 4] don't overlap as they share no common integers

Your goal is to count the total number of valid ways to perform this grouping. Since the answer can be astronomically large, return it modulo 109 + 7.

Input & Output

example_1.py โ€” Basic Case
$ Input: ranges = [[6,10],[5,15]]
โ€บ Output: 2
๐Ÿ’ก Note: The two ranges overlap ([5,15] contains [6,10]), so they must be in the same group. We can either put both in group A or both in group B, giving us 2 ways total.
example_2.py โ€” Non-overlapping Ranges
$ Input: ranges = [[1,3],[10,20],[2,5],[4,8]]
โ€บ Output: 4
๐Ÿ’ก Note: After sorting and merging: [1,3] merges with [2,5] and [4,8] to form [1,8]. [10,20] remains separate. Two independent components give us 2ยฒ = 4 ways to group them.
example_3.py โ€” Single Range
$ Input: ranges = [[1,1]]
โ€บ Output: 2
๐Ÿ’ก Note: With only one range, we can put it in either group A or group B, resulting in 2 possible ways.

Constraints

  • 1 โ‰ค ranges.length โ‰ค 104
  • ranges[i].length == 2
  • 0 โ‰ค starti โ‰ค endi โ‰ค 109
  • Time limit: 1 second

Visualization

Tap to expand
๐ŸŽ‰ Party Planning VisualizationOriginal Events (Overlapping Time Ranges)Birthday: 2-6pmDinner: 5-8pmMovie: 10-12pmConflict!After Merging ConflictsCombined: 2-8pmMovie: 10-12pmGroup Assignment Options (2ยฒ = 4 ways)List A: [2-8pm] | List B: [10-12pm]List A: [10-12pm] | List B: [2-8pm]List A: [2-8pm, 10-12pm] | List B: emptyList A: empty | List B: [2-8pm, 10-12pm]
Understanding the Visualization
1
Sort Events
Arrange all time ranges chronologically
2
Merge Conflicts
Combine overlapping time slots into single blocks
3
Count Blocks
Each merged block represents one independent group
4
Calculate Ways
With n independent blocks, we have 2^n assignment possibilities
Key Takeaway
๐ŸŽฏ Key Insight: Overlapping ranges must be grouped together, forming connected components. Each independent component can be assigned to either group, giving us 2^(components) total ways to split them.
Asked in
Google 42 Meta 35 Amazon 28 Microsoft 22
43.7K Views
Medium Frequency
~18 min Avg. Time
1.8K 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