Insert Interval

Greedy Algorithms Scheduling and Interval Problems Medium
  • This type of programming problem is used in various time scheduling applications, as seen in Google Calendar or Outlook, to prevent overlapping events and maintain them in sorted order
  • For instance, when a user wants to insert a new calendar event, the system will check if the time overlaps with other events, then if doesn't, the system inserts the event while preserving chronological order
  • So, such algorithms are essential to ensure effective time management in calendar-based applications

Given a 2D array Intervals, where Intervals[i] = [start[i], end[i]] represents the start and end of the ith interval, the array represents non-overlapping intervals sorted in ascending order by start[i]. 


Given another array newInterval, where newInterval = [start, end] represents the start and end of another interval, insert newInterval into Intervals such that Intervals remain non-overlapping and sorted in ascending order by start[i].


Return Intervals after the insertion of newInterval.

Examples:

Input : Intervals = [ [1, 3] , [6, 9] ] , newInterval = [2, 5]


Output : [ [1, 5] , [6, 9] ]


Explanation : After inserting the newInterval the Intervals array becomes [ [1, 3] , [2, 5] , [6, 9] ].

So to make them non overlapping we can merge the intervals [1, 3] and [2, 5].

So the Intervals array is [ [1, 5] , [6, 9] ].

Input : Intervals = [ [1, 2] , [3, 5] , [6, 7] , [8,10] ] , newInterval = [4, 8]


Output : [ [1, 2] , [3, 10] ]


Explanation : The Intervals array after inserting newInterval is [ [1, 2] , [3, 5] , [4, 8] , [6, 7] , [8, 10] ].

We merge the required intervals to make it non overlapping.

So final array is [ [1, 2] , [3, 10] ].

Input : Intervals = [ [1, 2] , [3, 5] , [6, 7] , [8,10] ] , newInterval = [1, 8]

Constraints

  • 0 <= Intervals.length <= 105
  • 0 <= start[i] < end[i] <= 107
  • 0 <= start < end <= 107
  • Intervals[i].length = 2
  • newInterval.length = 2

Hints

  • Since the input intervals are already sorted and non-overlapping, iterate through the intervals one by one. Compare the newInterval with each interval.
  • Update the start of newInterval to the minimum of its current start and the start of the overlapping interval. Update the end of newInterval to the maximum of its current end and the end of the overlapping interval. Skip the intervals that are merged into newInterval.

Company Tags

Shopify Alibaba Roblox American Express Riot Games Airbnb McKinsey & Company Bungie AMD Philips Healthcare Activision Blizzard Snowflake Mastercard Target eBay Lyft Oracle Intel Bloomberg Cloudflare Bain & Company Swiggy NVIDIA Deloitte Splunk Google Microsoft Amazon Meta Apple Netflix Adobe