Minimize Connected Groups by Inserting Interval - Problem
Minimize Connected Groups by Inserting Interval

You are given a collection of intervals and need to strategically add one new interval to minimize the number of connected groups.

What you're given:
• A 2D array intervals where intervals[i] = [start_i, end_i]
• An integer k representing the maximum length of the new interval

What you need to do:
Add exactly one new interval [start_new, end_new] such that:
1. The length end_new - start_new ≤ k
2. The number of connected groups is minimized

Connected Groups:
A connected group is a maximal collection of intervals that cover a continuous range with no gaps. For example:
[[1,2], [2,5], [3,3]] forms one connected group covering [1,5]
[[1,2], [4,5]] forms two connected groups due to the gap (2,4)

Goal: Return the minimum number of connected groups after adding your strategic interval.

Input & Output

example_1.py — Basic Gap Bridging
$ Input: intervals = [[1,3],[6,9]], k = 2
Output: 1
💡 Note: We can add interval [3,5] (length 2 ≤ k) to bridge the gap between [1,3] and [6,9], creating one connected group [1,9].
example_2.py — Multiple Gaps
$ Input: intervals = [[1,2],[4,5],[8,9]], k = 1
Output: 2
💡 Note: We can bridge either gap [2,4] or gap [5,8] with an interval of length 1. Bridging one gap reduces 3 groups to 2 groups. We cannot bridge both gaps with one interval.
example_3.py — No Bridging Possible
$ Input: intervals = [[1,2],[5,6]], k = 1
Output: 2
💡 Note: The gap between [1,2] and [5,6] is size 3, but k=1. We cannot bridge this gap, so we still have 2 separate groups. We must add an interval anyway, so it forms its own group or extends an existing one.

Constraints

  • 1 ≤ intervals.length ≤ 104
  • intervals[i].length == 2
  • 1 ≤ starti ≤ endi ≤ 105
  • 1 ≤ k ≤ 104
  • All interval endpoints are integers

Visualization

Tap to expand
🌉 Bridge Building StrategyNeighborhoods (Intervals):[1,3][7,9][15,18]Gaps to Bridge:Gap: 4 unitsGap: 6 unitsBudget Analysis (k=3):❌ Gap 1: 4 units > budget❌ Gap 2: 6 units > budget✅ Alternative: Extend existing intervalOptimal Solution:[4,7]← New bridge (length 3)Result: 3 groups → 2 groups
Understanding the Visualization
1
Survey the landscape
Identify existing connected neighborhoods (merged intervals)
2
Measure gaps
Calculate distances between separate neighborhoods
3
Check budget
Filter gaps that can be bridged within budget k
4
Build optimal bridge
Select the gap that connects the most areas
Key Takeaway
🎯 Key Insight: Focus on gaps between existing groups and choose the most impactful bridge within budget constraints.
Asked in
Google 42 Amazon 35 Microsoft 28 Meta 22
38.2K Views
Medium Frequency
~25 min Avg. Time
1.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen