Problem
You are given a 2D integer array intervals
where intervals[i] = [lefti, righti]
represents the inclusive interval [lefti, righti]
.
You have to divide the intervals into one or more groups such that each interval is in exactly one group, and no two intervals that are in the same group intersect each other.
Return the minimum number of groups you need to make.
Two intervals intersect if there is at least one common number between them. For example, the intervals [1, 5]
and [5, 8]
intersect.
Examples
Example 1:
|
|
Example 2:
|
|
Similar Problems
Meeting Rooms 1 - Can person attend all meetings Meeting Rooms II Maximum Population Year Describe the Painting Shifting Letters II The Skyline Problem My Calendar III Number of Flowers in Full Bloom Minimum Interval to Include Each Query
Solution
Method 1 - Sorting
Here is the approach:
- Definition of Intersection: Two intervals
[lefti, righti]
and[leftj, rightj]
intersect ifleftj <= righti
andlefti <= rightj
. - Greedy Approach:
- Sort the intervals based on their start times.
- Use a min-heap to keep track of the end times of intervals in the current groups.
- Iterate through each interval and check if it can be placed in any of the existing groups (represented by the heap).
- Detailed Steps:
- Sort the intervals based on their start times.
- Initialize a min-heap to track the earliest ending interval in each group.
- Iterate through the sorted intervals:
- Use the heap to check and remove any group that can accommodate the current interval.
- Add the current interval’s end time to the heap (representing a new or extended group).
- The size of the heap at the end of the iteration gives the minimum number of groups required.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
wheren
is the number of intervals. The sorting step takesO(n log n)
time, and each heap operation (insert and extract) isO(log n)
, leading to a total complexity for heap operations asO(n log n)
. - 🧺 Space complexity:
O(n)
, for storing intervals in the heap.