Sponsored
Sponsored
This approach involves sorting intervals by starting times and then greedily finding the minimum number of groups. When an interval starts after the end of another interval, they can be in the same group; otherwise, they need different groups.
The key insight is to manage the end times of groups using a priority queue (or a min-heap).
Time Complexity: O(n log n), due to sorting.
Space Complexity: O(n), for storing end times.
1import java.util.*;
2
3public class Solution {
4 public int minGroups(int[][] intervals) {
5 Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
6 PriorityQueue<Integer> pq = new PriorityQueue<>();
7 for (int[] interval : intervals) {
8 if (!pq.isEmpty() && pq.peek() < interval[0]) {
9 pq.poll();
10 }
11 pq.offer(interval[1]);
12 }
13 return pq.size();
14 }
15}
16
Similar to the C++ solution, this solution sorts the intervals based on start times and uses a priority queue for grouping based on end times. New non-overlapping groups are formed by polling the priority queue when possible (i.e., current start is after stored end).
This approach uses a sweep line algorithm where events are created for interval starts and ends. By tracking a count of ongoing intervals, the maximum number of overlapping intervals at any point can be determined, which corresponds to the minimum number of groups required.
It effectively converts the problem into finding the peak number of overlapping intervals.
Time Complexity: O(n log n) for sorting events.
Space Complexity: O(n), events list.
In Python, an events list is constructed similarly with increments and decrements at interval bounds, and the maximum number of overlapping intervals is found after sorting.