Problem Statement
leetcode problem link
Brute Force [Accepted]
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
res = []
intervals.append(newInterval)
intervals.sort()
for start, end in intervals:
if res and start <= res[-1][1]:
res[-1][1] = max(res[-1][1], end)
else:
res.append([start, end])
return res
Editorial
Approach 1: Linear Search
class Solution:
def insert(
self, intervals: List[List[int]], newInterval: List[int]
) -> List[List[int]]:
n = len(intervals)
i = 0
res = []
# Case 1: No overlapping before merging intervals
while i < n and intervals[i][1] < newInterval[0]:
res.append(intervals[i])
i += 1
# Case 2: Overlapping and merging intervals
while i < n and newInterval[1] >= intervals[i][0]:
newInterval[0] = min(newInterval[0], intervals[i][0])
newInterval[1] = max(newInterval[1], intervals[i][1])
i += 1
res.append(newInterval)
# Case 3: No overlapping after merging newInterval
while i < n:
res.append(intervals[i])
i += 1
return res
Approach 2: Binary Search
class Solution:
def insert(
self, intervals: List[List[int]], newInterval: List[int]
) -> List[List[int]]:
# If the intervals vector is empty, return a vector containing the newInterval
if not intervals:
return [newInterval]
n = len(intervals)
target = newInterval[0]
left, right = 0, n - 1
# Binary search to find the position to insert newInterval
while left <= right:
mid = (left + right) // 2
if intervals[mid][0] < target:
left = mid + 1
else:
right = mid - 1
# Insert newInterval at the found position
intervals.insert(left, newInterval)
# Merge overlapping intervals
res = []
for interval in intervals:
# If res is empty or there is no overlap, add the interval to the result
if not res or res[-1][1] < interval[0]:
res.append(interval)
# If there is an overlap, merge the intervals by updating the end of the last interval in res
else:
res[-1][1] = max(res[-1][1], interval[1])
return res