← Lessons

quiz vs the machine

Gold1360

Algorithms

Line Segment Intersection

Decide whether two segments cross using orientation tests, not slopes.

5 min read · core · beat Gold to climb

Crossing without slopes

Two line segments either cross, touch, or miss each other. Computing slopes invites division by zero for vertical lines and rounding trouble. The robust approach uses the orientation test on the endpoints, so the whole decision is signed area comparisons.

The general case

Label the segments and test how each segment's endpoints sit relative to the other:

  • Compute the orientation of the first segment with each endpoint of the second.
  • Compute the orientation of the second segment with each endpoint of the first.
  • If the two orientations differ in sign on both checks, the segments straddle each other and therefore intersect.

This straddling rule captures every proper crossing where the segments pass through each other's interior.

Collinear and touching cases

When an orientation comes out zero, the points are collinear and you must check whether an endpoint actually lies on the other segment, using a bounding box style range check. This handles overlaps and shared endpoints, the cases that trip up naive code. Treating these explicitly keeps the test correct on the boundary, not just in the clean middle case.

Key idea

Two segments cross when each straddles the other in the orientation tests, with collinear zeros handled by an explicit on segment range check.

Check yourself

Answer to earn rating on the learn ladder.

1. Why avoid using slopes to test segment intersection?

2. What does the straddling condition mean?

3. What does a zero orientation value force you to check?