Divide Intervals Into Minimum Number of Groups - Problem
Divide Intervals Into Minimum Number of Groups

You are given a 2D integer array intervals where intervals[i] = [lefti, righti] represents an inclusive interval [lefti, righti].

Your task is to organize these intervals into groups such that:
โ€ข Each interval belongs to exactly one group
โ€ข No two intervals in the same group intersect (overlap)

Two intervals intersect if they share at least one common point. For example, [1, 5] and [5, 8] intersect at point 5.

Goal: Return the minimum number of groups needed to organize all intervals.

Example: If you have intervals [[5,10],[6,8],[1,5],[2,3],[1,10]], you need 3 groups because at most 3 intervals overlap at any given time.

Input & Output

example_1.py โ€” Basic Overlap
$ Input: intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]]
โ€บ Output: 3
๐Ÿ’ก Note: At time 6, intervals [5,10], [6,8], and [1,10] all overlap, requiring 3 groups. This is the maximum overlap, so we need exactly 3 groups total.
example_2.py โ€” No Overlaps
$ Input: intervals = [[1,3],[5,6],[8,10],[11,13]]
โ€บ Output: 1
๐Ÿ’ก Note: All intervals are non-overlapping, so they can all be placed in a single group.
example_3.py โ€” Edge Case: Single Point
$ Input: intervals = [[1,1],[2,2],[3,3]]
โ€บ Output: 1
๐Ÿ’ก Note: Each interval is a single point and they don't overlap, so only 1 group is needed.

Visualization

Tap to expand
๐Ÿข Conference Center Room ManagementFinding minimum rooms for overlapping meetingsMeeting Schedule Timeline9 AM10 AM11 AM12 PM1 PMMarketing MeetingDesign ReviewAll-Hands Meeting1:1 SessionPeak: 3 meetingsNeed 3 rooms minimum๐Ÿ’ก Key InsightThe minimum number of groups equals the maximum number ofoverlapping intervals at any point in time
Understanding the Visualization
1
Convert to Events
Each meeting becomes two events: 'meeting starts' and 'meeting ends'
2
Sort by Time
Process all events in chronological order
3
Track Active Meetings
At any time, count how many meetings are running simultaneously
4
Find Peak Usage
The maximum simultaneous meetings = minimum rooms needed
Key Takeaway
๐ŸŽฏ Key Insight: By tracking when intervals start and end, we can efficiently find the peak overlap without checking every pair of intervals.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยฒ)

We check every pair of intervals, resulting in nร—n comparisons

n
2n
โš  Quadratic Growth
Space Complexity
O(1)

Only using a few variables to track maximum overlap count

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค intervals.length โ‰ค 105
  • intervals[i].length == 2
  • 1 โ‰ค lefti โ‰ค righti โ‰ค 106
  • Note: Intervals are inclusive on both ends
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
42.0K Views
High Frequency
~18 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen