Problem Description
Given an array of intervals where each interval is defined as [left, right] (inclusive), the goal is to partition these intervals into the minimum number of groups such that no two intervals in the same group intersect. Two intervals intersect if they share at least one common number.
Key Insights
- The minimum number of groups required is equivalent to the maximum number of overlapping intervals at any point in time.
- By processing the intervals using a sweep line technique (or sorted endpoints), one can track how many intervals are active concurrently.
- Sorting the start and end points separately (or handling them as events) allows for efficient counting of overlaps.
- Greedy decisions based on interval endpoints eliminate unnecessary overlaps in groups.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting of events. Space Complexity: O(n) for storing the events.
Solution
The solution uses a sweep line algorithm. First, transform the intervals into two events per interval (one for the start and one for the end). Sort these events such that when a start and an end event coincide, the start event is processed first (because [a, b] overlaps with an interval beginning at b). As you iterate over these events, maintain a counter for active intervals. The maximum counter value observed is the minimum number of groups needed since it represents the worst-case scenario of concurrent overlapping intervals.
Alternatively, a min-heap (priority queue) can also be used:
- Sort intervals by their starting point.
- Use the heap to store the end points of intervals currently in a group.
- For each interval, if the heap’s smallest end point is less than the current interval’s start, you can reuse that group (pop from heap) and push the new end. Otherwise, allocate a new group (push the new end).
- The size of the heap at the end is the number of groups needed.
Both approaches yield O(n log n) time complexity.