Advertisement
2406. Divide Intervals Into Minimum Number of Groups
MediumView on LeetCode
Time: O(n log n)
Space: O(n)
Approach
Sort by start; use min-heap of end times; each overlapping interval needs a new group.
2406.cs
C#
// Approach: Sort by start; use min-heap of end times; each overlapping interval needs a new group.
// Time: O(n log n) Space: O(n)
public class Solution
{
public int MinGroups(int[][] intervals)
{
// Stores `right`s.
PriorityQueue<int, int> minHeap = new PriorityQueue<int, int>();
Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));
foreach (var interval in intervals)
{
// There's no overlap, so we can reuse the same group.
if (minHeap.Count > 0 && interval[0] > minHeap.Peek())
minHeap.Dequeue();
minHeap.Enqueue(interval[1], interval[1]);
}
return minHeap.Count;
}
}Advertisement
Was this solution helpful?