Insert Interval
You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval. Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary). Return `intervals` after the insertion. **Examples:** ```typescript insert([[1,3],[6,9]], [2,5]) // [[1,5],[6,9]] insert([[1,2],[3,5],[6,7],[8,10],[12,16]], [4,8]) // [[1,2],[3,10],[12,16]] ```
Solve It in the BrowserPractice Explaining It Out Loud
Optimal Approach
- Time complexity: O(n)
- Space complexity: O(n)
Single linear pass through the intervals list of length n.
Follow-Up Questions Interviewers Ask About Insert Interval
- Could binary search be used to locate the insertion position?
Yes, binary search can locate where newInterval starts in O(log n), but merging overlapping intervals still takes O(n) worst case.
Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.