Skip to content
DeepForgeby svx
All problems
MediumAlgorithmsal-324

Axis-Aligned Segment Intersections

Problem

Count how many pairs of segments intersect, where horizontal segments are [x1, x2, y] and vertical segments are [x, y1, y2].

A horizontal and vertical segment cross when the vertical x lies between the horizontal endpoints and the horizontal y lies between the vertical endpoints, including endpoints. Brute force over the two lists is fine.

Hint

Parallel segments never intersect, so only horizontal-vertical pairs need checking.

Test cases

case 1
in: [[[0,2,1]],[[1,0,2]]]
expected: 1
case 2
in: [[[0,2,1],[0,2,1]],[[1,0,2]]]
expected: 2
case 3
in: [[],[[1,0,1]]]
expected: 0
case 4
in: [[[0,1,0]],[[1,0,1]]]
expected: 1
case 5
in: [[[0,1,0]],[[2,0,1]]]
expected: 0
Starter codePython
def axis_aligned_intersections(horizontal, vertical):
    # Your code here
    pass

5 test cases · run your code against them in the editor