Divide Intervals Into Minimum Number of Groups — LeetCode 2406 Python Solution

MediumGreedyArrayTwo PointersPrefix SumSortingHeap (Priority Queue)
Problem
#2406
Pattern
Prefix Sum
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n \times \log n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview