Problem Description
Given an array of points representing the vertices of a simple polygon (i.e., the polygon does not intersect itself except at adjacent vertices), determine if the polygon is convex. A polygon is convex if every internal angle is less than 180 degrees, meaning that for every set of three consecutive points, the turn is in the same direction (either all clockwise or all counter-clockwise).
Key Insights
- The polygon is convex if the cross product of every pair of consecutive edges has the same sign.
- Calculate the cross product for each trio of consecutive points to detect the turn direction.
- Use modulo arithmetic to manage wrapping from the last vertex to the first.
- Skip cross products that are zero (collinear points) in the consistency check.
Space and Time Complexity
Time Complexity: O(n), where n is the number of vertices.
Space Complexity: O(1) (constant extra space usage).
Solution
The solution involves iterating through each vertex and computing the cross product of vectors formed by three consecutive vertices. The sign of the cross product indicates a clockwise or counterclockwise turn. Initially, we establish a baseline direction from the first non-zero cross product. As we continue checking, if the sign deviates from the initial sign, the polygon is not convex and we return false. Otherwise, if all valid turns are consistent, the polygon is convex. This approach leverages simple arithmetic operations and a single loop, ensuring the algorithm runs in linear time with constant space.