This problem asks to determine if a polygon, defined by a sequence of points, is convex. A polygon is convex if all its interior angles are less than 180 degrees. We can efficiently solve this using the cross product.
Approach:
The core idea is to calculate the cross product of consecutive vectors formed by the polygon's vertices. The cross product of two vectors (x1, y1)
and (x2, y2)
is given by x1*y2 - x2*y1
. The sign of the cross product indicates the orientation of the turn between the vectors:
For a convex polygon, all turns must be consistently clockwise or counter-clockwise. If we encounter a change in the direction of the turns (from positive to negative or vice versa), then the polygon is not convex.
Algorithm:
Initialization: We start by initializing pre
(previous cross product) to 0 and iterate through the points of the polygon.
Cross Product Calculation: For each point i
, we calculate the cross product of the vectors formed by (i, i+1)
and (i, i+2)
, where (i+1)
and (i+2)
are taken modulo n
(the number of points) to handle wraparound.
Orientation Check:
cur
is non-zero and its sign is opposite to the sign of pre
(meaning there's a change in turn direction), the polygon is not convex, and we return false
.cur
is non-zero, we update pre
with cur
to track the consistent orientation.cur
is zero, this indicates collinear points. We don't change pre
as it does not affect convexity in this specific context of simple polygons.Convexity Determination: If the loop completes without finding any sign changes, it implies all turns have consistent orientation, and the polygon is convex. We return true
.
Time Complexity Analysis:
The algorithm iterates through the points of the polygon once. Therefore, the time complexity is O(n), where n is the number of points.
Space Complexity Analysis:
The algorithm uses a constant amount of extra space to store variables (pre
, cur
). The space complexity is therefore O(1).
Code Explanation (Python):
class Solution:
def isConvex(self, points: List[List[int]]) -> bool:
n = len(points)
pre = cur = 0 # Initialize previous and current cross products
for i in range(n):
x1 = points[(i + 1) % n][0] - points[i][0] # vector (i, i+1)
y1 = points[(i + 1) % n][1] - points[i][1]
x2 = points[(i + 2) % n][0] - points[i][0] # vector (i, i+2)
y2 = points[(i + 2) % n][1] - points[i][1]
cur = x1 * y2 - x2 * y1 # Cross product
if cur != 0: #Skip if points are collinear
if cur * pre < 0: # Check for sign change
return False
pre = cur # Update previous cross product
return True #Polygon is convex if no sign change detected
The code in other languages (Java, C++, Go) follows the same algorithm and logic, with only syntactic differences. The essential parts – cross-product calculation and orientation checking – remain identical across all implementations.