Convex Polygon

A polygon is convex if and only if the cross product of every three consecutive vertices has the same sign (either positive or negative). We can determine the sign of the cross product by evaluating the z-coordinate of the cross product of vectors formed by three consecutive vertices.

Here’s how you can implement the method:

  1. Create a helper function to calculate the cross product.
  2. Iterate through the polygon, taking three consecutive points at a time, and check the sign of the cross product.
  3. If at any point you find the cross products have different signs, return False. Otherwise, return True.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution:
    def isConvex(self, points: List[List[int]]) -> bool:
        def cross_product(p1, p2, p3):
            return (p2[0] - p1[0]) * (p3[1] - p1[1]) - (p2[1] - p1[1]) * (p3[0] - p1[0])

        n = len(points)
        last_sign = 0

        for i in range(n):
            # Taking three consecutive points
            p1, p2, p3 = points[i], points[(i + 1) % n], points[(i + 2) % n]
            sign = cross_product(p1, p2, p3)

            # If the cross product is zero, continue to the next iteration
            if sign == 0:
                continue

            # If the last_sign is not initialized, initialize it with the current sign
            if last_sign == 0:
                last_sign = sign

            # If the signs are different, return False
            if sign * last_sign < 0:
                return False

            last_sign = sign

        return True

This code checks if the given polygon is convex by computing the cross product for three consecutive vertices and ensuring that the sign of the cross product is consistent across all vertices.