2651. Count Ways to Group Overlapping Ranges
My accepted Python solution to LeetCode problem 2651, Count Ways to Group Overlapping Ranges, running in 19ms.
- Difficulty: Medium
- Python
- Runtime 19ms
- Memory 45.7MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 19ms, memory 45.7MB, accepted 2025-12-31.
class Solution:
def countWays(self, ranges: List[List[int]]) -> int:
MOD = 10**9 + 7
# Sort ranges by start time
ranges.sort()
# Merge overlapping ranges to count independent groups
groups = 0
current_end = -1
for start, end in ranges:
if start > current_end:
# New group
groups += 1
current_end = end
else:
# Extend current group
current_end = max(current_end, end)
# Each group can go to either group 1 or group 2
# Answer is 2^groups
return pow(2, groups, MOD)