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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int MinGroups(int[][] intervals) {
6 Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));
7 var pq = new SortedSet<int>();
8 foreach (var interval in intervals) {
9 if (pq.Count > 0 && pq.Min < interval[0]) {
10 pq.Remove(pq.Min);
11 }
12 pq.Add(interval[1]);
13 }
14 return pq.Count;
15 }
16}
17
In C#, the SortedSet class is used to apply a similar logic to that of the priority queue. This tracks and maintains a sorted order of 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.