LeetCode 57: Insert Interval — Python Solution

LeetCode 57: Insert Interval is a Medium intervals problem. This Python walkthrough develops a three-phase interval scan solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicIntervals
Reusable patternthree-phase interval scan
ComplexityO(n) time and O(n) output space

Recognizing the pattern

Sorting interval boundaries exposes a monotonic frontier: once an interval begins beyond it, earlier intervals cannot overlap again.

For this problem specifically, append intervals ending before the new one, merge every overlap into the new interval, then append the remaining intervals. The invariant worth writing beside the code is: Before the merge phase, output intervals are disjoint and strictly before the interval being inserted.

Step-by-step algorithm

  1. Identify the input state consumed by insert(intervals, newInterval) and initialize the data required by the three-phase interval scan pattern.
  2. Append intervals ending before the new one, merge every overlap into the new interval, then append the remaining intervals.
  3. After each update, verify the page’s central invariant: Before the merge phase, output intervals are disjoint and strictly before the interval being inserted.
  4. Finish only after the boundary behavior is covered: The new interval can belong first, last, or cover every existing interval.

Python solution

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:]

Reading the implementation

The main entry point is insert(intervals, newInterval). The named working state includes answer; those variables make the three-phase interval scan state visible instead of hiding it in incidental control flow.

The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, append intervals ending before the new one, merge every overlap into the new interval, then append the remaining intervals.

Correctness argument

Initialization. Before the scan begins, the unresolved range contains every candidate and the processed range is empty, so no answer has been lost.

Preservation. Append intervals ending before the new one, merge every overlap into the new interval, then append the remaining intervals. The chosen movement discards only candidates that cannot improve the answer; afterward, before the merge phase, output intervals are disjoint and strictly before the interval being inserted.

Termination. A boundary advances on every iteration. Once the active range is exhausted, every viable candidate was either measured or safely eliminated, so the stored result is optimal.

Complexity and trade-offs

O(n) time and O(n) output space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

Checking every pair avoids sorting but does quadratic work and complicates transitive overlaps. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().insert([[1,3],[6,9]],[2,5]) == [[1,5],[6,9]]

Common mistakes and edge cases

  • Problem-specific boundary: The new interval can belong first, last, or cover every existing interval.
  • Pattern-level pitfall: State whether touching endpoints count as overlap and preserve the appropriate endpoint when merging.
  • Invariant check: after every update, confirm that before the merge phase, output intervals are disjoint and strictly before the interval being inserted.

Interview review checklist

  • Explain why three-phase interval scan matches the structure of this input.
  • State the invariant in one sentence before tracing code: Before the merge phase, output intervals are disjoint and strictly before the interval being inserted.
  • Derive O(n) time and O(n) output space from how many times each element or state is visited.
  • Test the boundary explicitly: The new interval can belong first, last, or cover every existing interval.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 56. Merge Intervals · Next: 452. Minimum Number of Arrows to Burst Balloons