Bird
Raised Fist0

Which line contains the subtle bug that can cause incorrect merges when intervals just touch at boundaries?

medium🐞 Bug Identification Q7 of Q15
Intervals - Insert Interval
Consider this buggy insert interval code snippet. Which line contains the subtle bug that can cause incorrect merges when intervals just touch at boundaries? ```python def insert(intervals, newInterval): 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 with condition: if intervals[i][0] < merged[-1][1]:
BLine appending newInterval to intervals
CLine sorting intervals by start time
DLine appending intervals[i] to merged list
Step-by-Step Solution
Solution:
  1. Step 1: Analyze merge condition

    The condition uses '<' instead of '<=' which fails to merge intervals that just touch at boundaries.
  2. Step 2: Impact of bug

    Intervals like [1,3] and [3,5] won't merge incorrectly, causing wrong output.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Correct merge condition must use '<=' to merge touching intervals [OK]
Quick Trick: Use '<=' to merge intervals touching at boundaries [OK]
Common Mistakes:
MISTAKES
  • Using strict '<' causes missed merges at boundaries
Trap Explanation:
PITFALL
  • Candidates overlook boundary condition, causing subtle merge bugs.
Interviewer Note:
CONTEXT
  • Tests attention to detail in boundary conditions for merging.
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