Skip to content

Commit a9281b6

Browse files
committed
Adding Efficient Solution for Problem - 57 - Insert Interval
1 parent bbbbf7b commit a9281b6

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Insert_Interval/EfficientSolution.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
##==================================
2+
## Leetcode
3+
## Student: Vandit Jyotindra Gajjar
4+
## Year: 2020
5+
## Problem: 57
6+
## Problem Name: Insert Interval
7+
##===================================
8+
#Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
9+
#
10+
#You may assume that the intervals were initially sorted according to their start times.
11+
#
12+
#Example 1:
13+
#
14+
#Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
15+
#Output: [[1,5],[6,9]]
16+
#
17+
#Example 2:
18+
#
19+
#Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
20+
#Output: [[1,2],[3,10],[12,16]]
21+
#Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
22+
class Solution:
23+
def insert(self, intervals, newInterval):
24+
l, r = [], [] #Initialize l and r empty list
25+
intervals.sort(key = lambda x:x[0]) #Sort the intervals by its 1st element in sublists
26+
for i in intervals: #Loop through intervals
27+
if i[1] < newInterval[0]: #Condition-check: If i's last element is less than newInterval's first element
28+
l.append(i) #We append i in l
29+
elif i[0] > newInterval[1]: #Condition-check: Elif i's first element is greater than newInterval's last element
30+
r.append(i) #We append i in r
31+
else:
32+
newInterval = [min(newInterval[0], i[0]), max(newInterval[1], i[1])] #Update the newInterval by taking min and max of newInterval and i's first and last element resepectively
33+
return l + [newInterval] + r #Return the final list

0 commit comments

Comments
 (0)