![]() |
VOOZH | about |
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]] ]
👁 1
Output: No
Explanation: The given line segments are parallel to each other.👁 2
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.
We are going to use the below concept of orientation to solve this problem.
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)
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.
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:
👁 Image2. 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.
No
Time Complexity: O(1)
Space Complexity: O(1)