Leetcode #2580: Count Ways to Group Overlapping Ranges
In this guide, we solve Leetcode #2580 Count Ways to Group Overlapping Ranges in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Sorting
Intuition
Sorting reveals structure that is hard to see in the original order.
Once sorted, a linear scan is usually enough to compute the answer.
Approach
Sort the data and sweep through it while maintaining a small state.
This keeps the logic straightforward and reliable.
Steps:
- Sort the data.
- Scan in order while maintaining state.
- Update the best answer.
Example
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.
Python Solution
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)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.