What if you could add new events to your schedule without worrying about overlaps or order?
Why Insert Interval into Sorted List in DSA Python?
Imagine you have a list of booked meeting times sorted by start time. You want to add a new meeting without messing up the order or overlapping times.
Manually checking where to put the new meeting and merging overlapping times is slow and easy to mess up. You might forget to merge intervals or place the new one in the wrong spot.
Using the Insert Interval method, you can quickly find the right place to add the new meeting and merge any overlaps automatically, keeping the list sorted and clean.
intervals = [[1,3],[6,9]] new_interval = [2,5] # Manually check and merge intervals one by one
def insert_interval(intervals, new_interval): result = [] i = 0 while i < len(intervals) and intervals[i][1] < new_interval[0]: result.append(intervals[i]) i += 1 while i < len(intervals) and intervals[i][0] <= new_interval[1]: new_interval[0] = min(new_interval[0], intervals[i][0]) new_interval[1] = max(new_interval[1], intervals[i][1]) i += 1 result.append(new_interval) while i < len(intervals): result.append(intervals[i]) i += 1 return result
This method lets you keep a sorted list of intervals updated efficiently, perfect for scheduling and timeline management.
Adding a new appointment to your calendar without overlapping or losing existing bookings.
Manually inserting intervals is error-prone and slow.
Insert Interval method merges overlaps and keeps order automatically.
Useful for managing schedules, timelines, and bookings.