#2406
Divide Intervals Into Minimum Number of Groups
MediumArrayTwo PointersGreedySortingHeap (Priority Queue)Prefix SumGreedySortingHeap (Priority Queue)
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal approach uses sorting and a priority queue to efficiently manage overlapping intervals. By tracking the end times of intervals, we can determine the maximum number of overlapping intervals at any point.
⚙️
Algorithm
3 steps- 1Step 1: Sort the intervals based on their start times.
- 2Step 2: Use a priority queue (min-heap) to track the end times of the current groups.
- 3Step 3: For each interval, check if it can fit into an existing group (i.e., if its start time is greater than the smallest end time in the heap). If it can, replace that end time; otherwise, add a new group.
solution.py11 lines
1# Full working Python code
2import heapq
3
4def minGroups(intervals):
5 intervals.sort(key=lambda x: x[0])
6 min_heap = []
7 for interval in intervals:
8 if min_heap and min_heap[0] < interval[0]:
9 heapq.heappop(min_heap)
10 heapq.heappush(min_heap, interval[1])
11 return len(min_heap)ℹ
Complexity note: The sorting step takes O(n log n), and managing the heap takes O(n) in total, leading to an overall complexity of O(n log n).
- 1The problem is about managing overlapping intervals efficiently.
- 2Using a priority queue helps in tracking the end times of intervals, allowing for quick decisions on grouping.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.