Bird
Raised Fist0

Identify the subtle bug that causes incorrect output on some inputs: def merge(intervals): if not intervals: return [] intervals.sort(key=lambda x: x[0]) index = 0 for i in range(1, len(intervals)): if intervals[i][0] < intervals[index][1]: intervals[index][1] = max(intervals[index][1], intervals[i][1]) else: index += 1 intervals[index] = intervals[i] return intervals[:index+1]

medium🐞 Bug Identification Q7 of Q15
Intervals - Merge Intervals
Consider the following code snippet for in-place merging intervals. Identify the subtle bug that causes incorrect output on some inputs: def merge(intervals): if not intervals: return [] intervals.sort(key=lambda x: x[0]) index = 0 for i in range(1, len(intervals)): if intervals[i][0] < intervals[index][1]: intervals[index][1] = max(intervals[index][1], intervals[i][1]) else: index += 1 intervals[index] = intervals[i] return intervals[:index+1]
AReturning intervals[:index+1] slices too many intervals
BUsing '<' instead of '<=' in the overlap condition causes missing merges for touching intervals
CNot sorting intervals before merging causes incorrect merges
DUpdating intervals[index][1] with max is incorrect; should use min
Step-by-Step Solution
Solution:
  1. Step 1: Analyze overlap condition

    The code uses 'if intervals[i][0] < intervals[index][1]:' which excludes intervals that touch at endpoints (e.g., [1,3] and [3,5]).
  2. Step 2: Consequence of bug

    Intervals that share endpoints but do not strictly overlap are not merged, causing incorrect output.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Overlap condition must use '<=' to merge touching intervals [OK]
Quick Trick: Overlap check must include equality to merge touching intervals [OK]
Common Mistakes:
MISTAKES
  • Using strict less-than instead of less-or-equal
  • Forgetting to sort before merge
Trap Explanation:
PITFALL
  • Candidates often overlook that intervals touching at endpoints should merge, missing the '=' in condition.
Interviewer Note:
CONTEXT
  • Tests ability to spot subtle off-by-one style bugs in interval merging logic.
Master "Merge Intervals" 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