VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solution-line-segment-intersection/

⇱ CSES Solution - Line Segment Intersection - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solution - Line Segment Intersection

Last Updated : 23 Jul, 2025

There are two line segments: the first goes through the points (x1,y1) and (x2,y2), and the second goes through the points (x3,y3) and (x4,y4).

Your task is to determine if the line segments intersect, i.e., they have at least one common point.

Example:

Input: points = {1, 1}, {5, 3}, {1, 2}, {4, 3}
Output: No

Input: points = {1, 1}, {5, 3}, {1, 1}, {4, 3}
Output: No

Approach:

  • The main idea is to use the concept of cross products to determine if the line segments intersect.
  • Calculate the cross products of the vectors AB and AC, and CD and AB.
  • Check if the cross products have different signs, If the signs of the cross products are different, it means that the line segments intersect.
  • Check if any of the cross products is zero, then check if the point C or D lies on the line segment AB or point A or B lies on the line segment CD. If so, the line segments intersect.
  • Return "YES" if the line segments intersect, and "NO" otherwise.

Steps-by-step approach:

  • Calculate the cross products of AB and CD, AB and DA, CD and AB, and CD and BA.
  • Check if any of the cross products are zero and if the corresponding points are midpoints.
    • Return true
  • Check if the signs of the cross products are different for AB and CD, and for CD and AB.
    • Return true
  • Otherwise, Return false

Below are the implementation of the above approach:


Output
NO

Time complexity: O(n log n).
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: