#57

Insert Interval

Medium
ArrayTwo PointersArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach leverages the sorted nature of the intervals to efficiently insert and merge the new interval in a single pass, resulting in better performance.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an empty list for the result.
  2. 2Step 2: Iterate through the existing intervals and add them to the result until you find an interval that overlaps with the new interval.
  3. 3Step 3: Merge the overlapping intervals with the new interval.
  4. 4Step 4: Add any remaining intervals to the result.
solution.py13 lines
1def insert(intervals, newInterval):
2    merged = []
3    i = 0
4    while i < len(intervals) and intervals[i][1] < newInterval[0]:
5        merged.append(intervals[i])
6        i += 1
7    while i < len(intervals) and intervals[i][0] <= newInterval[1]:
8        newInterval[0] = min(newInterval[0], intervals[i][0])
9        newInterval[1] = max(newInterval[1], intervals[i][1])
10        i += 1
11    merged.append(newInterval)
12    merged.extend(intervals[i:])
13    return merged

Complexity note: The complexity is O(n) because we only make a single pass through the intervals, and O(n) space is used for the result list.

  • 1The intervals are sorted, which allows for efficient merging.
  • 2Merging can be done in a single pass if we handle overlaps correctly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.