Line Segment Intersection - Problem

Determine if two line segments intersect. Given two line segments defined by their endpoints, return true if they intersect, false otherwise.

Each line segment is defined by two points: [(x1, y1), (x2, y2)] for the first segment and [(x3, y3), (x4, y4)] for the second segment.

Special cases to handle:

  • Segments are collinear (lie on the same line)
  • Segments touch only at endpoints
  • One or both segments are actually points (zero length)
  • Segments overlap partially or completely

Return true for any intersection, including touching at endpoints.

Input & Output

Example 1 — Basic Intersection
$ Input: segment1 = [[0,0],[4,3]], segment2 = [[2,0],[2,4]]
Output: true
💡 Note: The first segment goes from (0,0) to (4,3), the second goes from (2,0) to (2,4). They intersect at point (2, 1.5).
Example 2 — No Intersection
$ Input: segment1 = [[0,0],[2,2]], segment2 = [[3,3],[5,5]]
Output: false
💡 Note: Both segments lie on the same line y = x but don't overlap - there's a gap between (2,2) and (3,3).
Example 3 — Endpoint Touch
$ Input: segment1 = [[0,0],[2,2]], segment2 = [[2,2],[4,0]]
Output: true
💡 Note: The segments meet exactly at point (2,2) where the first ends and second begins.

Constraints

  • -104 ≤ coordinates ≤ 104
  • Segments can have zero length (point)
  • Handle floating point precision carefully

Visualization

Tap to expand
INPUTALGORITHMRESULT(0,0)(4,3)(2,0)(2,4)Segment 1: [[0,0],[4,3]]Segment 2: [[2,0],[2,4]]1Calculate Orientations2Check Straddle Condition3Handle Special Cases4Return Intersection ResulttrueSegments IntersectThe segments cross at point(2, 1.5) in their interiorKey Insight:Two segments intersect if they straddle each other - orientation tests using cross productsdetermine which side of each line the other segment's endpoints lie on.TutorialsPoint - Line Segment Intersection | Orientation-Based Method
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
28.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen