Skip to content

Commit 6af8c54

Browse files
author
Joseph Luce
authored
Create 056_merge_intervals.md
1 parent 425607e commit 6af8c54

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# 56. Merge Intervals
2+
3+
## Solution
4+
- Runtime: O(Nlog(N))
5+
- Space: O(1) (Assuming result isn't considered extra space)
6+
- N = Number of elements in intervals
7+
8+
By sorting the intervals, we can then recreate the result by comparing previous intervals with the current interval from left to right.
9+
In this way, we can check if the two intervals overlap each other after the sort.
10+
11+
```
12+
class Solution:
13+
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
14+
if len(intervals) == 0:
15+
return []
16+
intervals.sort(key=lambda x: x[0])
17+
result = list()
18+
new_interval = intervals[0]
19+
for interval in intervals[1:]:
20+
if interval[0] <= new_interval[1]: # do they overlap?
21+
new_interval[1] = max(interval[1], new_interval[1])
22+
else:
23+
result.append(new_interval)
24+
new_interval = interval
25+
result.append(new_interval)
26+
return result
27+
```
28+
29+
## Brownie Points
30+
You can do some more optimizations for some inputs if you mention binary search.
31+
Since after the sort, we can binary search to find the index of the furthest right interval that is overlapping or itself.

0 commit comments

Comments
 (0)