The Indian Engineer

Problem 2406 Divide Intervals Into Minimum Number of Groups

Problem Statement

Link - Problem 2406

Question

You are given a 2D integer array intervals where intervals[i] = [lefti, righti] represents the inclusive interval [lefti, righti].

You have to divide the intervals into one or more groups such that each interval is in exactly one group, and no two intervals that are in the same group intersect each other.

Return the minimum number of groups you need to make.

Two intervals intersect if there is at least one common number between them. For example, the intervals [1, 5] and [5, 8] intersect.

 

Example 1:

Input: intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]]
Output: 3
Explanation: We can divide the intervals into the following groups:
- Group 1: [1, 5], [6, 8].
- Group 2: [2, 3], [5, 10].
- Group 3: [1, 10].
It can be proven that it is not possible to divide the intervals into fewer than 3 groups.

Example 2:

Input: intervals = [[1,3],[5,6],[8,10],[11,13]]
Output: 1
Explanation: None of the intervals overlap, so we can put all of them in one group.

 

Constraints:

Solution

class Solution {
public:
    int minGroups(vector<vector<int>>& inter) {
        int n = inter.size();

        sort(inter.begin(), inter.end());

        priority_queue<int, vector<int>, greater<int>> pq;

        for(int i = 0; i < n; i++) {
            int l = inter[i][0];
            int r = inter[i][1];

            if(pq.empty()){
                pq.push(r);
            }
            else{
                if(pq.top() >= l){
                    pq.push(r);
                }
                else{
                    pq.pop();
                    pq.push(r);
                }
            }
        }
        return pq.size();
    }
};

Complexity Analysis

| Algorithm                | Time Complexity | Space Complexity |
| ------------------------ | --------------- | ---------------- |
| Greedy Interval Coloring | O(n log n)      | O(n)             |

Explanation

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Medium difficulty.

Hints

Can you find a different way to describe the question?

The minimum number of groups we need is equivalent to the maximum number of intervals that overlap at some point. How can you find that?


Similar Questions:

Title URL Difficulty
Merge Intervals https://leetcode.com/problems/merge-intervals Medium
Minimum Number of Frogs Croaking https://leetcode.com/problems/minimum-number-of-frogs-croaking Medium
Average Height of Buildings in Each Segment https://leetcode.com/problems/average-height-of-buildings-in-each-segment Medium