Bird
Raised Fist0

Consider the following buggy code for inserting an interval. Which line contains the subtle bug that can cause incorrect output when the input list is empty?

medium🐞 Bug Identification Q14 of Q15
Intervals - Insert Interval
Consider the following buggy code for inserting an interval. Which line contains the subtle bug that can cause incorrect output when the input list is empty?
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
ALine 5: merged = [intervals[0]]
BLine 3: intervals.append(newInterval)
CLine 7: if intervals[i][0] <= merged[-1][1]:
DLine 9: merged.append(intervals[i])
Step-by-Step Solution
Solution:
  1. Step 1: Consider empty intervals input

    If intervals is empty, after appending newInterval, intervals has length 1.
  2. Step 2: Check initialization of merged

    Line 5 accesses intervals[0] without checking if intervals is empty before append, which is safe here but if input was empty, intervals[0] is newInterval, so no crash.
  3. Step 3: Identify subtle bug

    Actually, no crash here, but if input intervals was empty, sorting and merging still works. The subtle bug is that if intervals was empty and newInterval is appended, the code works, but if the initial intervals list is empty and the code did not append newInterval first, line 5 would crash. So the bug is that the code assumes intervals is non-empty before append, which is not always true.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Accessing intervals[0] without empty check is risky [OK]
Quick Trick: Accessing intervals[0] without empty check causes bug [OK]
Common Mistakes:
MISTAKES
  • Not handling empty input intervals list
  • Assuming intervals always non-empty before append
  • Incorrect merging when intervals just touch
Trap Explanation:
PITFALL
  • Option B looks like normal initialization but fails on empty input; others are correct lines.
Interviewer Note:
CONTEXT
  • Tests if candidate spots subtle assumptions about input validity and empty lists.
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