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
19
class Solution {
 public:
  // Similar to 253. Meeting Rooms II
  int minGroups(vector<vector<int>>& intervals) {
    // Stores `right`s.
    priority_queue<int, vector<int>, greater<>> minHeap;

    ranges::sort(intervals);

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

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

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

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

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

    for left, right in sorted(intervals):
      # There's no overlap, so we can reuse the same group.
      if minHeap and left > minHeap[0]:
        heapq.heappop(minHeap)
      heapq.heappush(minHeap, right)

    return len(minHeap)