Bird
Raised Fist0

Consider this buggy code snippet for removing covered intervals:

medium🐞 Bug Identification Q14 of Q15
Intervals - Remove Covered Intervals
Consider this buggy code snippet for removing covered intervals:
def remove_covered_intervals(intervals):
    intervals.sort(key=lambda x: (x[0], x[1]))  # Bug here
    count = 0
    max_end = 0
    for _, end in intervals:
        if end > max_end:
            count += 1
            max_end = end
    return count
What is the bug in this code?
AThe condition 'if end > max_end' should be 'if end >= max_end' to include equal ends.
Bmax_end is not updated correctly inside the loop.
CSorting by end ascending instead of descending causes coverage detection failure.
DThe nested loop for coverage check is missing, causing incorrect results.
Step-by-Step Solution
  1. Step 1: Analyze sorting key

    Sorting by (start ascending, end ascending) orders intervals with same start from shortest to longest, which breaks coverage detection.
  2. Step 2: Understand coverage detection logic

    Coverage detection relies on intervals with same start being sorted longest first (end descending) so covered intervals come after.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Sorting end ascending causes missed coverage when starts equal [OK]
Quick Trick: Sort end descending to detect coverage correctly [OK]
Common Mistakes:
MISTAKES
  • Sorting end ascending instead of descending
  • Using strict inequality incorrectly
Trap Explanation:
PITFALL
  • Sorting end ascending looks natural but breaks coverage detection for intervals with equal starts.
Interviewer Note:
CONTEXT
  • Checks if candidate knows the critical sorting order for coverage detection.
Master "Remove Covered 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