Minimize Connected Groups by Inserting Interval - Problem
You are given a 2D array intervals, where intervals[i] = [starti, endi] represents the start and the end of interval i. You are also given an integer k.
You must add exactly one new interval [startnew, endnew] to the array such that:
- The length of the new interval,
endnew - startnew, is at mostk. - After adding, the number of connected groups in intervals is 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.
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.
Input & Output
Example 1 — Bridge Two Groups
$
Input:
intervals = [[1,3],[5,7]], k = 2
›
Output:
1
💡 Note:
Original has 2 groups: [1,3] and [5,7]. Gap between them is (3,5) with size 2. We can add [3,5] (length=2≤k) to connect both groups into one.
Example 2 — Cannot Bridge Fully
$
Input:
intervals = [[1,2],[6,8]], k = 2
›
Output:
2
💡 Note:
Gap is (2,6) with size 4 > k=2. Best we can do is add [2,4] or [4,6], but this creates 3 total groups. Better to add [1,1] (extends first group) keeping 2 groups.
Example 3 — Already Connected
$
Input:
intervals = [[1,5],[3,7]], k = 1
›
Output:
1
💡 Note:
Intervals overlap, so already 1 connected group. Adding any new interval keeps it at 1 group minimum.
Constraints
- 0 ≤ intervals.length ≤ 104
- intervals[i].length == 2
- -109 ≤ starti ≤ endi ≤ 109
- 0 ≤ k ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Groups
Original intervals form separate connected groups
2
Find Gap
Identify gap between groups that can be bridged
3
Bridge Gap
Add new interval to connect groups and minimize total count
Key Takeaway
🎯 Key Insight: The optimal strategy is to identify gaps between separate groups and bridge them with the new interval to maximize group merging
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code