Skip to content

2406. Divide Intervals Into Minimum Number of Groups 👍

  • Time: $O(n\log n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  // Very simliar to 253. Meeting Rooms II
  int minGroups(vector<vector<int>>& intervals) {
    // Store `right`s
    priority_queue<int, vector<int>, greater<>> minHeap;

    sort(begin(intervals), end(intervals));

    for (const vector<int>& interval : intervals) {
      if (!minHeap.empty() && interval[0] > minHeap.top())
        minHeap.pop();  // No overlap, we can reuse the same group
      minHeap.push(interval[1]);
    }

    return minHeap.size();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  // Very simliar to 253. Meeting Rooms II
  public int minGroups(int[][] intervals) {
    // Store `right`s
    Queue<Integer> minHeap = new PriorityQueue<>((a, b) -> a - b);

    Arrays.sort(intervals, (a, b) -> (a[0] - b[0]));

    for (int[] interval : intervals) {
      if (!minHeap.isEmpty() && interval[0] > minHeap.peek())
        minHeap.poll(); // No overlap, we can reuse the same group
      minHeap.offer(interval[1]);
    }

    return minHeap.size();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  # Very simliar to 253. Meeting Rooms II
  def minGroups(self, intervals: List[List[int]]) -> int:
    minHeap = []  # Store `right`s

    for left, right in sorted(intervals):
      if minHeap and left > minHeap[0]:
        heapq.heappop(minHeap)
      heapq.heappush(minHeap, right)

    return len(minHeap)