Divide Intervals Into Minimum Number of Groups — LeetCode 2406 Python Solution
- Problem
- #2406
- Pattern
- Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]]
- Output
- 3
- Explanation
- We can divide the intervals into the following groups:
Python solution
class Solution:
def minGroups(self, intervals: List[List[int]]) -> int:
q = []
for left, right in sorted(intervals):
if q and q[0] < left:
heappop(q)
heappush(q, right)
return len(q)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 2406. Divide Intervals Into Minimum Number of Groups is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2406. Divide Intervals Into Minimum Number of Groups?
- LeetCode 2406. Divide Intervals Into Minimum Number of Groups is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2406. Divide Intervals Into Minimum Number of Groups?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2406. Divide Intervals Into Minimum Number of Groups?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2406. Divide Intervals Into Minimum Number of Groups cover?
- LeetCode 2406. Divide Intervals Into Minimum Number of Groups is tagged Greedy, Array, Two Pointers, Prefix Sum, Sorting and Heap (Priority Queue) on LeetCode.