2580. Count Ways to Group Overlapping Ranges

Difficulty:
Related Topics:
Similar Questions:

Problem

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:

Two ranges are said to be overlapping if there exists at least one integer that is present 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.

Example 1:

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.

Example 2:

Input: ranges = [[1,3],[10,20],[2,5],[4,8]]
Output: 4
Explanation:
Ranges [1,3], and [2,5] are overlapping. So, they must be in the same group.
Again, ranges [2,5] and [4,8] are also overlapping. So, they must also be in the same group.
Thus, there are four possible ways to group them:
- All the ranges in group 1.
- All the ranges in group 2.
- Ranges [1,3], [2,5], and [4,8] in group 1 and [10,20] in group 2.
- Ranges [1,3], [2,5], and [4,8] in group 2 and [10,20] in group 1.

Constraints:

Solution (Java)

class Pair{
    int arrive;
    int depart;
    Pair(int arrive,int depart){
        this.arrive=arrive;
        this.depart=depart;
    }
}
class Solution {
    public int pow(int a, int b, int m){
        if(b==0)
            return 1;
        if(b==1)
            return a;
        Long res=new Long(pow(a,b/2,m));
        res=(res*res)%m;
        if(b%2==1){
            res=(res*a)%m;
        }
        return res.intValue();
    }
    public int countWays(int[][] ranges) {
        List<Pair> store=new ArrayList<>();
        for(int i=0;i<ranges.length;i++){
            store.add(new Pair(ranges[i][0],ranges[i][1]));
        }
        Collections.sort(store,(a,b)->a.arrive-b.arrive);
        List<Pair> ans=new ArrayList<>();
        int arrived=store.get(0).arrive;
        int departed=store.get(0).depart;
        for(Pair p:store){
            if(departed>=p.arrive){
                arrived=Math.min(arrived,p.arrive);
                departed=Math.max(departed,p.depart);
            }
            else{
                ans.add(new Pair(arrived,departed));
                arrived=p.arrive;
                departed=p.depart;
            }
        }
        ans.add(new Pair(arrived,departed));
        int arr[][]=new int[ans.size()][2];
        int k=0;
        for(Pair x: ans){
            arr[k][0]=x.arrive;
            arr[k][1]=x.depart;
            k++;
        }
        return pow(2,arr.length,(int)(1e9+7));
    }
}

Explain:

nope.

Complexity: