Bird
Raised Fist0

Examine the following buggy code snippet for the minimum interval problem. Which line contains the subtle bug that can cause incorrect results on some inputs?

medium🐞 Bug Identification Q14 of Q15
Intervals - Minimum Interval to Include Each Query
Examine the following buggy code snippet for the minimum interval problem. Which line contains the subtle bug that can cause incorrect results on some inputs?
def min_interval_binary_search(intervals, queries):
    intervals.sort(key=lambda x: x[1] - x[0] + 1)
    lengths = [end - start for start, end in intervals]
    starts = [start for start, end in intervals]
    ends = [end for start, end in intervals]

    def covers(query, length):
        idx = bisect.bisect_right(lengths, length)
        for i in range(idx):
            if starts[i] <= query <= ends[i]:
                return True
        return False

    res = []
    max_len = lengths[-1] if lengths else 0
    for q in queries:
        left, right = 1, max_len
        ans = -1
        while left <= right:
            mid = (left + right) // 2
            if covers(q, mid):
                ans = mid
                right = mid - 1
            else:
                left = mid + 1
        res.append(ans)
    return res
ALine 15: max_len = lengths[-1] if lengths else 0
BLine 2: intervals.sort(key=lambda x: x[1] - x[0] + 1)
CLine 9: for i in range(idx):
DLine 3: lengths = [end - start for start, end in intervals]
Step-by-Step Solution
Solution:
  1. Step 1: Check interval length calculation

    Line 3 calculates lengths as end - start, missing the +1 needed for inclusive intervals.
  2. Step 2: Impact of bug

    Incorrect lengths cause wrong sorting order and coverage checks, leading to wrong minimal interval lengths.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Correct interval length must be end - start + 1 [OK]
Quick Trick: Check interval length calculation carefully [OK]
Common Mistakes:
MISTAKES
  • Off-by-one in length calculation
  • Not sorting intervals
  • Incorrect binary search boundaries
Trap Explanation:
PITFALL
  • The length calculation looks plausible but misses the inclusive +1, a common off-by-one error.
Interviewer Note:
CONTEXT
  • Tests ability to spot subtle off-by-one bugs that break correctness.
Master "Minimum Interval to Include Each Query" 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