Learn Code
Depth-First Search
Greedy Algorithms
Intervals
Insert Interval
medium
DESCRIPTION (credit Leetcode.com)
Given a list of intervals intervals and an interval newInterval, write a function to insert newInterval into a list of existing, non-overlapping, and sorted intervals based on their starting points. The function should ensure that after the new interval is added, the list remains sorted without any overlapping intervals, merging them if needed.
Input:
Output:
Explanation: The new interval [2,5] overlaps with [1,3], so they are merged into [1,5].
Explanation
- Add all the intervals ending before newInterval starts to merged.
- Merge all overlapping intervals with newInterval and add that merged interval to merged.
- Add all the intervals starting after newInterval to merged.
Phase 1
initialize variables
0 / 1
Phase 2
add intervals before newInterval
0 / 4
Phase 3
j = 4
0 / 2
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(n) where n
is the number of intervals. We iterate through all intervals once to merge them.
Space Complexity: O(n) where n
is the number of intervals. We need space for the merged
output array.
Solution
insert interval
0 / 9
Login to track your progress
Your account is free and you can post anonymously if you choose.