Minimize Connected Groups by Inserting Interval Problem
Description
LeetCode Problem 3323.
You are given a 2D array intervals, where intervals[i] = [start_i, end_i] represents the start and the end of interval i. You are also given an integer k.
You must add exactly one new interval [start_new, end_new] to the array such that:
- The length of the new interval,
end_new - start_new, is at mostk. - After adding, the number of connected groups in
intervalsis minimized.
A connected group of intervals is a maximal collection of intervals that, when considered together, cover a continuous range from the smallest point to the largest point with no gaps between them. Here are some examples:
- A group of intervals
[[1, 2], [2, 5], [3, 3]]is connected because together they cover the range from 1 to 5 without any gaps. - However, a group of intervals
[[1, 2], [3, 4]]is not connected because the segment(2, 3)is not covered.
Return the minimum number of connected groups after adding exactly one new interval to the array.
Example 1:
Input: intervals = [[1,3],[5,6],[8,10]], k = 3
Output: 2
Explanation:
After adding the interval [3, 5], we have two connected groups: [[1, 3], [3, 5], [5, 6]] and [[8, 10]].
Example 2:
Input: intervals = [[5,10],[1,1],[3,3]], k = 1
Output: 3
Explanation:
After adding the interval [1, 1], we have three connected groups: [[1, 1], [1, 1]], [[3, 3]], and [[5, 10]].
Constraints:
1 <= intervals.length <= 10^5intervals[i] == [start_i, end_i]1 <= start_i <= end_i <= 10^91 <= k <= 10^9
Solution
Approach: Sorting + Binary Search
Sort the intervals by start and merge the overlapping ones into disjoint groups merged. Without any insertion the answer is len(merged).
The inserted interval has length at most k. If its left end is placed at the end e of group i, it can reach as far as e + k, so it touches every following group whose start is at most e + k. Use binary search to find j, the first group whose start is at least e + k + 1. The groups i + 1 .. j - 1 are then joined with group i by the new interval, so the group count becomes len(merged) - (j - i - 1). Take the minimum over all i.
Complexity: O(n log n) time and O(n) space, where n is the number of intervals.
from bisect import bisect_left
class Solution:
def minConnectedGroups(self, intervals: List[List[int]], k: int) -> int:
intervals.sort()
merged = [intervals[0]]
for s, e in intervals[1:]:
if merged[-1][1] < s:
merged.append([s, e])
else:
merged[-1][1] = max(merged[-1][1], e)
ans = len(merged)
for i, (_, e) in enumerate(merged):
j = bisect_left(merged, [e + k + 1, 0])
ans = min(ans, len(merged) - (j - i - 1))
return ans