Day-7 Leetcode Coding Journey: Mastering Problem-Solving Techniques
Leetcode #56 Merge Intervals
Problem Statement:
Given a collection of intervals, merge all overlapping intervals and return an array of the non-overlapping intervals that cover all the intervals in the input.
Constraints
1 ≤ intervals.length ≤ 10^4
intervals[i].length == 2
-10^4 ≤ intervals[i][0] ≤ intervals[i][1] ≤ 10^4
🚀 Code Implementation
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
intervals.sort(key=lambda x: x[0])
merged=[]
for interval in intervals:
if not merged or merged[-1][1]<interval[0]:
merged.append(interval)
else:
merged[-1][1]=max(merged[-1][1],interval[1])
return merged
Leetcode #57 Insert Interval
Problem Statement:
Given a set of non-overlapping intervals and a new interval, insert the new interval into the intervals such that the resulting intervals remain non-overlapping and sorted by the start time.
Constraints
1 ≤ intervals.length ≤ 10^4
intervals[i].length == 2
-10^4 ≤ intervals[i][0] ≤ intervals[i][1] ≤ 10^4
The input list of intervals is already sorted by the start time.
🚀 Code Implementation
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[List[int]]
:type newInterval: List[int]
:rtype: List[List[int]]
"""
result=[]
i=0
while i<len(intervals) and intervals[i][1] < newInterval[0]:
result.append(intervals[i])
i=i+1
while i<len(intervals) and intervals[i][0]<=newInterval[1]:
newInterval[0] = min(newInterval[0],intervals[i][0])
newInterval[1] = max(newInterval[1],intervals[i][1])
i=i+1
result.append(newInterval)
while i<len(intervals):
result.append(intervals[i])
i=i+1
return result