Bird
Raised Fist0

What subtle bug causes incorrect counts for points exactly at interval ends?

medium🐞 Bug Identification Q7 of Q15
Intervals - Count of Intervals Containing Each Point
The following code attempts to count intervals containing each point using line sweep. What subtle bug causes incorrect counts for points exactly at interval ends? ```python def count_intervals_bug(intervals, points): events = [] for start, end in intervals: events.append((start, 1, -1)) events.append((end, -1, -1)) # Bug here: end instead of end+1 for i, p in enumerate(points): events.append((p, 0, i)) events.sort(key=lambda x: (x[0], -x[1])) active = 0 result = [0] * len(points) for coord, typ, idx in events: if typ == 1: active += 1 elif typ == -1: active -= 1 else: result[idx] = active return result ```
AIncrementing active intervals on end event instead of decrementing
BSorting events by coordinate ascending instead of descending
CUsing end instead of end+1 for interval end event excludes points at interval end
DNot initializing result array with zeros
Step-by-Step Solution
Solution:
  1. Step 1: Identify event for interval end

    Using end instead of end+1 means points exactly at interval end are processed after the end event, missing coverage.
  2. Step 2: Effect on point coverage count

    Points at interval end see active intervals decremented before their event, causing undercount.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Correct end event must be at end+1 to include points at interval end [OK]
Quick Trick: End event must be at end+1 to include points at interval end [OK]
Common Mistakes:
MISTAKES
  • Placing end event at end instead of end+1
  • Misordering events causing off-by-one errors
  • Confusing event types in sorting
Trap Explanation:
PITFALL
  • Candidates often overlook that end event must be at end+1 to count points at interval end correctly.
Interviewer Note:
CONTEXT
  • Tests candidate's attention to subtle off-by-one bugs in event-based interval counting.
Master "Count of Intervals Containing Each Point" 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