#2580

Count Ways to Group Overlapping Ranges

Medium
ArraySortingSortingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution involves merging overlapping ranges and counting the number of distinct groups formed. This reduces the problem to a linear scan after sorting, making it efficient.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the ranges based on the start time.
  2. 2Step 2: Merge overlapping ranges into groups.
  3. 3Step 3: The number of ways to split the groups is 2 raised to the power of the number of merged groups.
solution.py15 lines
1# Full working Python code
2
3def countWays(ranges):
4    MOD = 10**9 + 7
5    ranges.sort(key=lambda x: x[0])
6    merged = []
7
8    for start, end in ranges:
9        if not merged or merged[-1][1] < start:
10            merged.append([start, end])
11        else:
12            merged[-1][1] = max(merged[-1][1], end)
13
14    return pow(2, len(merged), MOD)
15

Complexity note: The time complexity is O(n log n) due to sorting the ranges, and the space complexity is O(n) for storing the merged ranges.

  • 1Merging overlapping ranges reduces complexity.
  • 2The number of ways to split is based on the number of merged groups.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.