Solve LeetCode 57: Insert Interval in Python with a three-phase interval scan approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.
This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Intervals |
| Reusable pattern | three-phase interval scan |
| Complexity | O(n) time and O(n) output space |
What the problem is testing
Append intervals ending before the new one, merge every overlap into the new interval, then append the remaining intervals.
Algorithm
- Append intervals ending before the new one, merge every overlap into the new interval, then append the remaining intervals.
- Maintain this invariant: Before the merge phase, output intervals are disjoint and strictly before the interval being inserted.
- Continue until every input item or reachable state has been resolved, then return the accumulated result.
Python solution
from collections import Counter, defaultdict, deque, OrderedDict
import random
class Solution:
def insert(self, intervals, newInterval):
answer, i = [], 0
while i < len(intervals) and intervals[i][1] < newInterval[0]:
answer.append(intervals[i]); i += 1
while i < len(intervals) and intervals[i][0] <= newInterval[1]:
newInterval[0] = min(newInterval[0], intervals[i][0])
newInterval[1] = max(newInterval[1], intervals[i][1]); i += 1
return answer + [newInterval] + intervals[i:]Why this is correct
The proof follows the maintained state: Before the merge phase, output intervals are disjoint and strictly before the interval being inserted. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.
Complexity
O(n) time and O(n) output space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.
Edge cases
The new interval can belong first, last, or cover every existing interval.
Tested reference code
This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 56. Merge Intervals · Next: 452. Minimum Number of Arrows to Burst Balloons