Skip to content

Commit 2fa7218

Browse files
committed
added Insert Interval (hard)
1 parent 677aa8b commit 2fa7218

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

Hard/InsertInterval/README.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
2+
# Insert Interval
3+
[Leetcode Link](https://leetcode.com/problems/insert-interval/)
4+
5+
## Problem:
6+
7+
Given a set of *non-overlapping* intervals, insert a new interval into the intervals (merge if necessary).
8+
9+
You may assume that the intervals were initially sorted according to their start times.
10+
11+
## Example:
12+
13+
```
14+
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
15+
Output: [[1,5],[6,9]]
16+
```
17+
```
18+
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
19+
Output: [[1,2],[3,10],[12,16]]
20+
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
21+
```

Hard/InsertInterval/solution.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from typing import List
2+
3+
class Solution:
4+
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
5+
result = list()
6+
# insert newInterval sorted by start time
7+
insertIndex = 0
8+
for i, interval in enumerate(intervals):
9+
if newInterval[0] >= interval[0]:
10+
insertIndex = i+1
11+
intervals.insert(insertIndex, newInterval)
12+
print(intervals)
13+
# use queue to merge from low start time
14+
while intervals:
15+
cur = intervals.pop(0)
16+
if not result:
17+
result.append(cur)
18+
continue
19+
if result[-1][0] <= cur[0] <= result[-1][1]:
20+
start = result[-1][0]
21+
end = max(result[-1][1], cur[1])
22+
result[-1] = [start, end]
23+
else:
24+
result.append(cur)
25+
return result
26+
27+
28+
# test driver
29+
sol = Solution()
30+
intervals = [[2,3], [6,8]]
31+
newInterval = [4,7]
32+
print("Output:", sol.insert(intervals, newInterval))

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ Languages used: Java and Python
7777
- [Reducing Dishes](Hard/ReducingDishes)
7878
- [Longest Consecutive Sequence](Hard/LongestConsecutiveSequence)
7979
- [First Missing Positive](Hard/FirstMissingPositive)
80+
- [Insert Interval](Hard/InsertInterval)
8081

8182
---
8283

0 commit comments

Comments
 (0)