For a not-convex polygon, the direction of travel changes: say, clockwise to counter-clockwise.

If we have three consecutive points , the sign of the cross product between the two consecutive vectors:
and
gives us the direction of travel. If the direction changes, we declare the polygon to be not-convex.
Time: , space:
.
class Solution:
def isConvex(self, points: List[List[int]]) -> bool:
n = len(points)
prev_dir = 0
for i in range(n):
p0, p1, p2 = points[i], points[(i+1)%n], points[(i+2)%n]
x1, y1 = (p1[0]-p0[0]), (p1[1]-p0[1])
x2, y2 = (p2[0]-p0[0]), (p2[1]-p0[1])
curr_dir = x1*y2 - x2*y1
if prev_dir * curr_dir < 0:
return False
prev_dir = prev_dir or curr_dir
return True
Leave a comment