MEDIUM NC#130 Blind #35 Intervals
57. Insert Interval
๐ Problem
You are given an array of non-overlapping intervals where intervals[i] = [start_i, end_i] sorted in ascending order by start_i, and a new interval newInterval = [start, end], insert newInterval into intervals if still sorted in ascending order by start_i and intervals still does not have any overlapping intervals (merge overlapping if needed). Return intervals after insertion.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ Add all intervals ending before new interval
- โ Merge all overlapping intervals
- โ Add all remaining intervals after new interval
- โ Time: O(n), Space: O(n) for result
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขAdd all intervals ending before new interval
- โขMerge all overlapping intervals
- โขAdd all remaining intervals after new interval
Common Pitfalls
- โขTime: O(n), Space: O(n) for result
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
insert([[1,3],[6,9]], [2,5]); Expected:
[[1,5], [6,9]] Test Case 2
Not run Input:
insert([[1,2],[3,5],[6,7],[8,10],[12,16]], [4,8]); Expected:
[[1,2], [3,10], [12,16]] Test Case 3
Not run Input:
insert([], [5,7]); Expected:
[[5,7]] ๐ Code Editor
๐ค Output