Solution: Convex Polygon
Let’s solve the Convex Polygon problem using the Math and Geometry pattern.
Statement
You are given an array of points on the XY plane, where each point is represented as points[i]
=
Your task is to return TRUE if the polygon is
Note: It is guaranteed that the polygon formed by the given points is simple, meaning exactly two edges intersect at each vertex, and the edges do not intersect with each other elsewhere.
Constraints:
points.length
points[i].length == 2
, All the given points are unique.
Solution
To determine whether a polygon is convex, the key idea is to analyze the cross product of vectors formed by three consecutive points. These cross products reveal the direction of turns between the points—consistently clockwise or counterclockwise. If the direction of all turns remains uniform throughout the polygon, it confirms that the polygon is convex.
The cross product of vectors formed by three points
If the cross product is positive, the turn is counterclockwise.
If the cross product is negative, the turn is clockwise.
If the cross product is zero, the points are
.collinear Collinear points lie on the same straight line.
The algorithm steps are as follows:
Initialize a variable
prev_cp
to. This variable will track the previous cross product. Iterate through the polygon points. For each point
points[i]
, calculate the cross productcp
with its previous and next points.If
cp
is, the points are collinear. In this case, skip them and proceed, as these three points do not define a direction. If
cp
is not: Check if
prev_cp
andcp
represent the same direction by multiplying them. If both are positive or both are negative, the product is positive. If one is positive and the other is negative, the product is negative, and we return FALSE.Otherwise, update
prev_cp
tocp
.
If all points have been processed without returning FALSE, return TRUE, indicating that the given points form a convex polygon.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.