Skip to main content
Back to problems
#2580
Medium Algorithms

Count ways to group overlapping ranges

Array Sorting
39.0% acceptance
Feb 25, 2026
339
27
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn count_ways(mut ranges: Vec<Vec<i32>>) -> i32 {
    const MOD: i64 = 1_000_000_007;
    ranges.sort_unstable_by_key(|r| r[0]);
    let mut groups = 0i64;
    let mut max_end = i32::MIN;
    for r in &ranges {
      if r[0] > max_end {
        groups += 1; // new independent group
      }
      max_end = max_end.max(r[1]);
    }
    // Each independent group can go to group 1 or group 2: 2^groups ways
    let mut result = 1i64;
    for _ in 0..groups { result = result * 2 % MOD; }
    result as i32
  }
}