Bird
Raised Fist0

What is the value of the variable removals after the second iteration of the loop when the input is [[1,3],[2,4],[3,5]]?

easy🧾 Code Trace Q12 of Q15
Intervals - Non-overlapping Intervals (Max Non-Overlap)
Consider the following Python function that returns the maximum number of non-overlapping intervals. What is the value of the variable removals after the second iteration of the loop when the input is [[1,3],[2,4],[3,5]]?
from typing import List

def max_non_overlapping_intervals(intervals: List[List[int]]) -> int:
    intervals.sort(key=lambda x: x[0])
    removals = 0
    last_end = intervals[0][1]
    for i in range(1, len(intervals)):
        if intervals[i][0] < last_end:
            removals += 1
            last_end = min(last_end, intervals[i][1])
        else:
            last_end = intervals[i][1]
    return len(intervals) - removals

intervals = [[1,3],[2,4],[3,5]]
print(max_non_overlapping_intervals(intervals))
A1
B3
C2
D0
Step-by-Step Solution
  1. Step 1: Trace first iteration (i=1)

    Intervals sorted by start: [[1,3],[2,4],[3,5]]. last_end=3. At i=1, intervals[1][0]=2 < 3, so removals=1, last_end=min(3,4)=3.
  2. Step 2: Trace second iteration (i=2)

    At i=2, intervals[2][0]=3 <= last_end=3 is false, so last_end=5, removals remains 1.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    removals incremented once at i=1 only [OK]
Quick Trick: Check overlap condition carefully at each iteration [OK]
Common Mistakes:
MISTAKES
  • Off-by-one error in loop iteration
  • Misunderstanding when to increment removals
  • Confusing last_end update logic
Trap Explanation:
PITFALL
  • Candidates often forget that intervals starting exactly at last_end do not overlap, so removals is not incremented.
Interviewer Note:
CONTEXT
  • Tests ability to mentally execute greedy interval removal code.
Master "Non-overlapping Intervals (Max Non-Overlap)" 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