Merge Intervals
Bernice Waweru
Posted on November 10, 2022
Instructions
Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Approach
Sort the input by starttime to have an ascending list for comparison.
Iterate through sorted intervals and if start of a given interval is less than or equal to the most recent end time stored in the result list then,update the previous end time(ie most recent end time in the result list) based on the max of current prevEnd and end of current interval.
If condition is not met append interval to result.
Implementation
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort()
result = [intervals[0]]
for start,end in intervals[1:]:
prevEnd = result[-1][1]
if start <= prevEnd:
result[-1][1] = max(prevEnd,end)
else:
result.append([start,end])
return result
Happy coding !!
Posted on November 10, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024
November 30, 2024