Below is a structured article addressing the problem, including intuition, algorithm, a dry run, code implementation in C++, and complexity analysis.
The problem is about merging intervals with a twist: we are adding a new interval to an already sorted list of intervals. Intervals may overlap with the new one, and the goal is to ensure the final list is sorted and does not contain any overlapping intervals.
Think of the intervals on a timeline. Inserting the new interval is like identifying where it belongs on the timeline and merging any overlaps that result.
The key insight:
start
and end
of the new interval to cover the merged range.Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]]
, newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]