Leetcode 2406: Divide Intervals Into Minimum Number of Groups

grid47
grid47
Exploring patterns and algorithms
Mar 11, 2024 7 min read

You are given a 2D array of intervals, where each interval is represented as a pair of integers [left, right], denoting an inclusive range. Your task is to divide these intervals into the minimum number of groups such that no two intervals within the same group overlap. Two intervals overlap if there is at least one common number between them.
Problem
Approach
Steps
Complexity
Input: The input consists of a 2D array `intervals` where each element `intervals[i]` is an array of two integers, left and right, representing the start and end of an interval.
Example: intervals = [[1, 5], [6, 10], [3, 7], [8, 12], [15, 18]]
Constraints:
• 1 <= intervals.length <= 10^5
• Each interval is represented by two integers where 1 <= lefti <= righti <= 10^6
Output: Return the minimum number of groups required to partition the intervals such that no two intervals within the same group overlap.
Example: Output: 3
Constraints:
Goal: The goal is to minimize the number of groups while ensuring that no two intervals within the same group overlap.
Steps:
• 1. Sort the intervals by their start times.
• 2. Use a priority queue (min-heap) to track the end times of intervals in each group.
• 3. For each interval, check if it can be added to an existing group (i.e., its start time is greater than the smallest end time in the heap).
• 4. If it can, update the group's end time; otherwise, start a new group.
• 5. Keep track of the maximum number of groups at any time.
Goal: The solution should be able to handle the maximum constraints efficiently.
Steps:
• The time complexity of the solution should be O(n log n), where n is the number of intervals.
Assumptions:
• Intervals are inclusive of both left and right endpoints.
• The input list will not contain empty intervals.
Input: intervals = [[5, 10], [6, 8], [1, 5], [2, 3], [1, 10]]
Explanation: We can divide the intervals into the following groups: Group 1: [1, 5], [6, 8]; Group 2: [2, 3], [5, 10]; Group 3: [1, 10]. Thus, 3 groups are needed.

Input: intervals = [[1, 3], [5, 6], [8, 10], [11, 13]]
Explanation: Since none of the intervals overlap, all intervals can be placed in one group.

Input: intervals = [[1, 4], [3, 5], [5, 6], [7, 8]]
Explanation: The optimal partition is: Group 1: [1, 4], [5, 6]; Group 2: [3, 5], [7, 8]. We need 2 groups.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus