Bird
Raised Fist0

Examine the following buggy code for interval intersections:

medium🐞 Bug Identification Q14 of Q15
Intervals - Interval List Intersections
Examine the following buggy code for interval intersections:
def intervalIntersection(A, B):
    i, j = 0, 0
    result = []
    while i < len(A) and j < len(B):
        if A[i][1] <= B[j][0]:
            i += 1
        elif B[j][1] < A[i][0]:
            j += 1
        else:
            start = max(A[i][0], B[j][0])
            end = min(A[i][1], B[j][1])
            result.append([start, end])
            if A[i][1] < B[j][1]:
                i += 1
            else:
                j += 1
    return result
What is the bug in this code?
AThe condition 'if A[i][1] <= B[j][0]' should use '<' instead of '<=' to correctly detect touching intervals.
BThe pointer increments inside the else block are reversed; they should increment the pointer with the larger endpoint.
CThe overlap condition should check 'start < end' instead of 'start <= end' to avoid zero-length intervals.
DThe code does not handle empty input lists, which can cause runtime errors.
Step-by-Step Solution
  1. Step 1: Analyze overlap condition

    Using '<=' excludes intervals that touch at a point (e.g., end == start), missing valid intersections.
  2. Step 2: Correct condition

    Changing to '<' ensures intervals that share a boundary point are considered intersecting.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Inclusive endpoints require '<' not '<=' to detect touching intervals [OK]
Quick Trick: Check boundary conditions carefully for inclusive intervals [OK]
Common Mistakes:
MISTAKES
  • Using <= instead of <
  • Reversing pointer increments
  • Ignoring empty inputs
Trap Explanation:
PITFALL
  • Using '<=' looks safer but misses intersections where intervals just touch at a point.
Interviewer Note:
CONTEXT
  • Tests attention to subtle boundary conditions in interval comparisons.
Master "Interval List Intersections" 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