Inserting Intervals: Merging and Maintaining Order

Inserting Intervals: Merging and Maintaining Order

Handling intervals is a common task in computational problems, particularly when working with scheduling or range-based queries.

In this article, we’ll address a classic interval problem: inserting a new interval into an existing list of non-overlapping, sorted intervals while ensuring the result is properly merged and remains sorted.

Problem Description

You are given:

  • A list of non-overlapping intervals, represented as intervals[i] = [start_i, end_i], where start_i and end_i are the start and end times of each interval.
    The intervals are sorted in ascending order by their start times.

  • A new interval, represented as newInterval = [start, end].

Task

Insert newInterval into intervals such that:

  1. The resulting list remains sorted by start times.
  2. Overlapping intervals are merged into a single interval.

Constraints

  • 0≤intervals.length≤1000
  • and newInterval.length=2
  • 0≤start≤end≤1000

Explanation:
The new interval [2,5] overlaps with both [1,3] and [4,6], so all three are merged into [1,6].

Explanation:
The new interval [6,7] does not overlap with any existing intervals, so it is simply inserted in its correct position.

Approach to Solve the Problem

To solve this problem, we need to carefully handle overlapping intervals and preserve the order of the list. Here’s a step-by-step breakdown:

Step 1: Identify Non-Overlapping Intervals

Before merging, we need to figure out:

  • Left Intervals: Intervals that end before the new interval starts. These don’t overlap with newInterval and can be added directly to the result.
  • Right Intervals: Intervals that start after the new interval ends. These also don’t overlap and can be added directly.

Step 2: Merge Overlapping Intervals

If an interval overlaps with the new interval, we merge them by:

  1. Taking the minimum of the start times.
  2. Taking the maximum of the end times.

We continue merging until there are no more overlapping intervals.

Step 3: Combine Results

Once we’ve processed the intervals, combine the left intervals, the merged interval, and the right intervals into a single sorted list.

There are mainly three approach to solve this problem – 

  1. Linear Search 
  2. Binary Search
  3. Greedy 

1. Linear Search 

  • Time complexity: O(n)
  • Space complexity: O(1)

2. Binary Search

Time & Space Complexity
  • Time complexity: O(n)
  • Space complexity: O(1)

Code

3. Greedy

  • Time complexity: O(n)
  • Space complexity: O(1)

More Articles