Bird
Raised Fist0

Given the following code for inserting an interval, what is the final returned list after calling insert([[1,3],[6,9]], [2,5])?

easy🧾 Code Trace Q12 of Q15
Intervals - Insert Interval
Given the following code for inserting an interval, what is the final returned list after calling insert([[1,3],[6,9]], [2,5])?
from typing import List

def insert(intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
    intervals.append(newInterval)
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for i in range(1, len(intervals)):
        if intervals[i][0] <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], intervals[i][1])
        else:
            merged.append(intervals[i])
    return merged
A[[1,5],[6,9]]
B[[1,3],[2,5],[6,9]]
C[[1,3],[6,9],[2,5]]
D[[1,9]]
Step-by-Step Solution
Solution:
  1. Step 1: Append and sort intervals

    After appending [2,5], intervals become [[1,3],[6,9],[2,5]]. Sorting by start time yields [[1,3],[2,5],[6,9]].
  2. Step 2: Merge overlapping intervals

    Start with merged = [[1,3]]. The next interval [2,5] overlaps since 2 <= 3, so merge to [1,5]. Next interval [6,9] does not overlap, so append it.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Result matches expected merged intervals [OK]
Quick Trick: Sort after insertion, then merge overlapping intervals [OK]
Common Mistakes:
MISTAKES
  • Not sorting after insertion leads to wrong order
  • Failing to merge intervals that overlap at boundaries
  • Appending newInterval multiple times
Trap Explanation:
PITFALL
  • Option A looks like the input with newInterval appended but not merged; common mistake is skipping merge step.
Interviewer Note:
CONTEXT
  • Tests ability to trace code and understand merging logic step-by-step.
Master "Insert Interval" in Intervals

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Intervals Quizzes