15% off all plans & roadmaps Use code

See plans

Divide Intervals Into Minimum Number of Groups

Updated

TL;DR: You must split the intervals into the fewest groups where no two intervals in a group share a number. The answer equals the largest number of intervals that all cover one point, so sorting the starts and ends finds it in O(n log n).

Problem

You get a 2D integer array intervals, where intervals[i] = [lefti, righti] is the inclusive interval from lefti to righti.

Split the intervals into one or more groups. Every interval must belong to exactly one group, and no two intervals in the same group may intersect. Two intervals intersect if they share at least one number. For example, [1, 5] and [5, 8] intersect.

Return the minimum number of groups you need.

Example 1

Input: intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]]
Output: 3
Explanation:
You can split the intervals into these groups:

- Group 1: [1, 5], [6, 8].
- Group 2: [2, 3], [5, 10].
- Group 3: [1, 10].

It can be proven that you cannot use fewer than 3 groups.

Example 2

Input: intervals = [[1,3],[5,6],[8,10],[11,13]]
Output: 1
Explanation: None of the intervals overlap, so all of them fit in one group.

Constraints

  • 1 <= intervals.length <= 10^5
  • intervals[i].length == 2
  • 1 <= lefti <= righti <= 10^6

Constraints that matter

  • n up to 10^5 rules out the O(n^2) pair checks of the brute force, which means about 10^10 operations in the worst case.
  • Coordinates go up to 10^6, so a counting array over every coordinate is possible in time, but it uses memory proportional to 10^6 and does not scale with n.
  • Intervals are inclusive, so an interval ending at 5 and one starting at 5 conflict. The comparison must be strict when you decide whether a group has closed.
  • Each interval has left at most right, so an interval never closes before it opens. This lets you count closed intervals with a single sorted array of ends.

View on LeetCode

Hints

Hint 1

Two intervals that share a number cannot sit in the same group.

Hint 2

The naive approach asks: for a given number x, how many intervals contain it?

Solution

Intuition

Two intervals that share a number cannot sit in the same group. So if one number lies inside k intervals, those k intervals need k different groups. The answer is at least the largest such count. This is an interval scheduling problem, and the busiest moment on the timeline sets the answer.

Picture a parking lot with two counters, one at the entrance and one at the exit. Each arriving car ticks the entrance counter, and each departing car ticks the exit counter. The entrance counter is the sorted starts, the exit counter is the sorted ends, so their difference is the number of cars inside right now.

The reverse also holds. Sweep the timeline from left to right, and give each new interval a group that has already finished. Open a new group only when every existing group still covers the current start. The number of groups you open equals the peak overlap, so the sweep gives the minimum.

What to notice in the statement: the order of the groups does not matter, and only overlap counts. That points to sorting the endpoints and making one scan, which is a greedy sweep. The sort is the expensive step, and the scan costs only linear time after it.

Watch the pattern animation

Worked example

Input: intervals = [[1,5],[1,5],[1,5],[1,5]]
Output: 4
Explanation: All four intervals are the same, and each one contains the number 1 through 5. Any two of them share numbers, so each needs its own group. The four intervals need four groups, and the answer is 4.

Approach 1: Brute force

The naive approach asks: for a given number x, how many intervals contain it? The largest such count is the answer, because intervals that share x must go into different groups. This version tries only each interval's left end as x, since the largest left end among the intervals covering any point is a left end all of them still cover.

What is slow: for every candidate x, the brute force rescans the whole list. The same intervals are checked again and again for each candidate, so the work grows with the square of n.

Steps

  1. Set best to 0.
  2. For each interval, take its left end as the candidate point x.
  3. Count the intervals [l, r] that satisfy l <= x <= r. Scan the whole list for every candidate.
  4. Store the largest count in best.
  5. Return best.

Dry run

The example has four copies of [1, 5], so every left end is 1. For the first candidate x = 1, all four intervals satisfy 1 <= 1 <= 5, so the count is 4 and best becomes 4. The other three candidates also count 4, so best stays 4. Return 4.

Complexity

TimeO(n^2)
SpaceO(1)

Let n be the number of intervals. The outer loop tries n candidate points, one for each left end. For each candidate, the inner loop checks all n intervals in constant time, which gives n * n checks in total. The algorithm stores only a few counters, so the extra space is O(1).

PythonTested in our runner

class Solution:
    def minGroups(self, intervals: List[List[int]]) -> int:
        best = 0
        for left, _ in intervals:
            # Count the intervals that contain this left end.
            count = 0
            for start, end in intervals:
                if start <= left <= end:
                    count += 1
            best = max(best, count)
        return best

The Interval Merging/Scheduling infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Interval Merging/Scheduling

Part of Greedy Patterns

Approach 2: Sort starts and ends, then two pointersOptimalInterval Merging/Scheduling

What is slow: the brute force rescans all intervals for each candidate. The insight that fixes it is to sort the starts and the ends separately. Then one pointer moves forward over the sorted ends, and the count at each start becomes a subtraction, with no rescans.

Count the intervals that cover a point x with two numbers. Take the intervals that start at or before x, and subtract the intervals that ended before x. An interval that ended before x also started before x, so the subtraction is exact. The count at x is the number of starts up to x minus the number of ends below x.

Why it is correct. Every interval that ended before x also started before x, so it was already counted among the starts up to x. Removing those closed intervals leaves exactly the intervals that start at or before x and still reach x. The answer is the largest such count, and checking each start point finds that peak.

Steps

  1. Copy every left end into starts and sort it.
  2. Copy every right end into ends and sort it, separately from starts.
  3. Set j to 0 (the number of intervals that have closed) and best to 0.
  4. For each index i from 0 to n - 1, let s = starts[i]. Advance j while ends[j] < s.
  5. Count the covering intervals at s as i + 1 - j, and store the largest value in best.
  6. Return best.

Dry run

The example gives starts = [1, 1, 1, 1] and ends = [5, 5, 5, 5]. No end is below any start, so j stays 0 throughout. The table shows each step.

istarts[i]jends[j] < starts[i]?i + 1 - jbest
0105 < 1? no11
1105 < 1? no22
2105 < 1? no33
3105 < 1? no44

The loop ends with best equal to 4. Return 4.

Complexity

TimeO(n log n)
SpaceO(n)

Let n be the number of intervals. Sorting starts and ends costs O(n log n) each, so the sorts take O(n log n) in total. The main loop runs n times, and j only moves forward, never passing i, so the scan is O(n) and the total is O(n log n). The two arrays hold n numbers each, so the space is O(n).

PythonTested in our runner

class Solution:
    def minGroups(self, intervals: List[List[int]]) -> int:
        starts = sorted(s for s, _ in intervals)
        ends = sorted(e for _, e in intervals)
        n = len(starts)
        j = 0      # number of intervals that have already closed
        best = 0
        for i in range(n):
            # Close every interval that ended before this start.
            while ends[j] < starts[i]:
                j += 1
            best = max(best, i + 1 - j)
        return best

Common mistakes

  • while ends[j] <= starts[i] closes intervals that end exactly where another starts. Intervals [1, 5] and [5, 8] share the number 5, so the end must stay open. Use the strict <.
  • return i - j or count = i - j drops the current start. A single interval [3, 3] would give 0 instead of 1. Add 1 for the interval at index i.
  • Sorting only the intervals by start and reading the ends in that order. The ends must be sorted on their own, because the pointer needs the smallest remaining end. Sort ends as a separate array.
  • Returning the count at the last start. For [1, 3], [1, 3], [4, 4], the last count is 1, but the answer is 2 from the first two intervals. Keep a running best and return it.
  • Switching to a min-heap of end times and writing heap[0] <= start as the reuse test. This reuses a group whose last interval still touches the new start. Use heap[0] < start.

Edge cases

  • One interval, such as [[3, 3]]. The answer is 1, and the count at index 0 is 1 - 0 = 1.
  • All intervals identical, such as four copies of [1, 5]. Every interval conflicts with every other, so the answer is 4.
  • Touching intervals, such as [[1, 5], [5, 8]]. They share the number 5, so the answer is 2.
  • Fully disjoint intervals, such as [[1, 3], [5, 6], [8, 10], [11, 13]]. Nothing overlaps, so the answer is 1.
  • Nested intervals, such as [[1, 10], [2, 3], [4, 5]]. The point 4 lies inside [1, 10] and [4, 5], so the answer is 2.
  • Maximum size: 100000 copies of [1, 1000000]. The answer is 100000, and all counts stay well inside a 32-bit integer.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Divide Intervals Into Minimum Number of Groups, with how to answer them.

Unlock the follow-ups

Divide Intervals Into Minimum Number of Groups FAQ

What is the time complexity of Divide Intervals Into Minimum Number of Groups?

The sorting two-pointer solution runs in O(n log n) time, because sorting two arrays of n numbers dominates the scan. The brute force runs in O(n^2) time. Both use the same input, so the difference comes from the repeated scans.

Why use sorting with two pointers for Divide Intervals Into Minimum Number of Groups?

Sorting the starts and ends puts them in order, so a single pointer can move forward over the ends. Each interval that closes is passed once. The count at each start then becomes one subtraction.

Can Divide Intervals Into Minimum Number of Groups be solved in O(1) extra space?

No known method here does it. The two-pointer approach needs sorted copies of the endpoints, which takes O(n) space. The counting approach needs an array over the coordinates, which grows with 10^6 and not with n.

Is the answer the same as the maximum number of overlapping intervals?

Yes. Intervals that share a number need separate groups, so the peak overlap is a lower bound. A sweep that reuses finished groups shows that this many groups are always enough.

Does a min-heap of end times also solve this problem?

Yes. Sort by start, then keep a min-heap of the end times of open groups. When the smallest end is strictly less than the next start, pop it, and always push the new end. The heap size at the end is the answer.

Asked at

See which companies ask this — Pro

Practise it