VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-two-given-line-segments-intersect/

⇱ How to check if two given line segments intersect? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to check if two given line segments intersect?

Last Updated : 23 Jul, 2025

Given two line segments represented as a 3D vector points[][][], where each line segment i is defined by its endpoints stored in points[i][0] and points[i][1] (each containing 2 integers), your task is to determine if these two line segments intersect with each other.

Examples:

Input: points[][][] = [ [[1, 1], [10, 1]] , [[1, 2], [10, 2]] ]
Output: No
Explanation: The given line segments are parallel to each other.

👁 1


Input: points[][][] = [ [[10, 0], [0, 10]] , [[0, 0], [10, 10]] ]
Output: Yes
Explanation: The given line segments are mirror image of each other and intersects at middle point.

👁 2

We are going to use the below concept of orientation to solve this problem.

Orientation of 3 Ordered Points

Orientation of an ordered triplet of points in the plane can be:

  • counterclockwise
  • clockwise
  • collinear

The following diagram shows different possible orientations of (a, b, c)

👁 Image

If orientation of (p1, p2, p3) is collinear, then orientation of (p3, p2, p1) is also collinear. 
If orientation of (p1, p2, p3) is clockwise, then orientation of (p3, p2, p1) is counterclockwise and vice versa is also true.

Using Orientation of Lines - O(1) Time and O(1) Space

The idea is to use orientation of lines to determine whether they intersect or not. Two line segments [p1, q1] and [p2, q2] intersects if and only if one of the following two conditions is verified:

1. General Case:-

  • [p1, q1, p2] and [p1, q1, q2] have different orientations.
  • [p2, q2, p1] and [p2, q2, q1] have different orientations.

Following image contains examples of general case:
👁 Image

2. Special Case:

  • [p1, q1, p2], [p1, q1, q2], [p2, q2, p1], and [p2, q2, q1] are all collinear.
  • The x-projections of [p1, q1] and [p2, q2] intersect.
  • The y-projections of [p1, q1] and [p2, q2] intersect.

Following image contains examples of special case:
👁 Image

Approach:

The idea is to firstly find the four orientations required to analyze general and special cases. We've discussed an approach to find orientation of 3 ordered points in article Orientation of 3 Ordered points. Thereafter, check for the general case, if both the conditions are true, return true, else check for special case. Now, for special case, the points must be collinear and the point should on the line segment. To check if the point lies on line segment, check if the point lies between max and min of x and y coordinates.


Output
No

Time Complexity: O(1)
Space Complexity: O(1)

Comment