Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] Output: [[1,2],[3,10],[12,16]] Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
Solution
Language: Java
This solution is quite straightforward, and it’s based on the non-overlapping feature.
Use a stack to store all items in intervals, make sure the item that has smaller index on top. And the stack concept can be realized using a real Stack or just use the index (because there is no push action).
Here are next steps:
Add all non-overlapping item with newInterval to result
While there is overlapping between newInterval and stack top, replace the newInterval with the overlapped result and pop stack. It ends when the stack is empty or there is no overlapping any more (remember, the origin intervals has no overlapping).