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.
1const minGroups = (intervals) => {
2 intervals.sort((a, b) => a[0] - b[0]);
3 const pq = [];
4 for (let [start, end] of intervals) {
5 if (pq.length > 0 && pq[0] < start) {
6 pq.shift();
7 }
8 pq.push(end);
9 pq.sort((a, b) => a - b);
10 }
11 return pq.length;
12};
13
The JavaScript solution uses array manipulation to simulate priority queue behavior by keeping an in-place sorted structure as the group ends with the same logic of removing when possible and adding new end times.
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.
The solution creates events for the start and the end (incremented by 1 for exclusive end point) of each interval. It sorts these events and uses a counter to track ongoing intervals, updating the maximum overlap found.