Problem Description
Given a list of intervals and an integer k, you must add exactly one new interval (of length at most k) such that after adding it, the number of connected groups formed by the intervals is minimized. A connected group is a maximal collection of intervals that together cover a continuous range with no gaps.
Key Insights
- First, merge the given intervals into connected groups.
- Each connected group is represented by its overall minimum start and maximum end.
- Gaps between adjacent groups represent the “distance” that separates them.
- The new interval, by design, can connect consecutive groups if its length is at least the gap between them.
- The problem boils down to finding the longest sequence of consecutive groups that can be merged using one new interval of length ≤ k.
- Use a two‑pointer or sliding window strategy over the sorted groups to find the maximum chain that can be connected.
Space and Time Complexity
Time Complexity: O(n log n) primarily due to sorting the intervals. Space Complexity: O(n) for storing the groups (in worst-case all intervals are non-overlapping).
Solution
- Sort the intervals by starting time.
- Merge overlapping or touching intervals into connected groups.
- For each group, determine its start and end.
- Use a two-pointer (sliding window) approach over the connected groups:
- For each starting group, try to extend the window by including subsequent groups.
- The condition to merge groups i to j is that the new interval must cover the gap from groups[i].end to groups[j].start. In other words, the required length is groups[j].start - groups[i].end.
- If this required length is ≤ k, the new interval could connect these groups.
- Track the maximum number of groups that can be merged.
- The final answer is the total number of connected groups minus (maxChain - 1) because merging maxChain groups reduces the total count by maxChain - 1.
Code Solutions
Below are implementations in Python, JavaScript, C++, and Java.