Divide Intervals Into Minimum Number of Groups - 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.
Input & Output
Example 1 — Basic Overlapping
$
Input:
intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]]
›
Output:
3
💡 Note:
We can divide into 3 groups: Group 1: [[1,5],[6,8]], Group 2: [[5,10]] (note [1,5] and [5,10] intersect at 5), Group 3: [[2,3],[1,10]] won't work since they overlap. Better grouping: Group 1: [[1,5]], Group 2: [[6,8]], Group 3: [[5,10],[2,3]] won't work. Optimal: Group 1: [[1,5],[6,8]], Group 2: [[2,3]], Group 3: [[5,10],[1,10]] - but [5,10] and [1,10] overlap. Actually: intervals [1,5], [2,3], [1,10] all overlap with each other, so need 3 groups minimum.
Example 2 — No Overlaps
$
Input:
intervals = [[1,3],[5,6],[8,10],[11,13]]
›
Output:
1
💡 Note:
No intervals overlap since each ends before the next begins, so all can go in one group: [[1,3],[5,6],[8,10],[11,13]]
Example 3 — Maximum Overlap
$
Input:
intervals = [[1,10],[2,10],[3,10],[4,10]]
›
Output:
4
💡 Note:
All intervals overlap with each other since they all contain points 4-10, so each needs its own group
Constraints
- 1 ≤ intervals.length ≤ 105
- intervals[i].length == 2
- 1 ≤ lefti ≤ righti ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input Intervals
Given intervals that may overlap with each other
2
Group Assignment
Assign each interval to a group where no two intervals overlap
3
Minimum Groups
Find the minimum number of groups needed
Key Takeaway
🎯 Key Insight: The minimum groups needed equals the maximum number of intervals overlapping at any single point in time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code