Bird
Raised Fist0

The following code attempts to merge intervals in-place after sorting. Identify the line that contains a subtle bug causing incorrect results on some inputs.

medium🐞 Bug Identification Q14 of Q15
Intervals - Merge Intervals
The following code attempts to merge intervals in-place after sorting. Identify the line that contains a subtle bug causing incorrect results on some inputs.
ALine 3: intervals.sort(key=lambda x: x[0])
BLine 9: intervals[index][1] = max(intervals[index][1], intervals[i][1])
CLine 12: return intervals # missing slicing after in-place merge
DLine 8: if intervals[i][0] <= intervals[index][1]:
Step-by-Step Solution
  1. Step 1: Understand the in-place merge modifies intervals up to index.

    After merging, only intervals[:index+1] are valid merged intervals.
  2. Step 2: Identify the bug in the return statement.

    Returning the entire intervals list without slicing includes extra unmerged intervals, causing incorrect output.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Return intervals[:index+1] to exclude leftover intervals. [OK]
Quick Trick: Return sliced intervals after in-place merge [OK]
Common Mistakes:
MISTAKES
  • Forgetting to slice after in-place merge
  • Modifying list while iterating without adjusting index
Trap Explanation:
PITFALL
  • Returning full list looks correct but includes stale intervals beyond merged index.
Interviewer Note:
CONTEXT
  • Tests attention to detail and understanding of in-place list modifications.
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