Convex Polygon Problem
Description
LeetCode Problem 469.
You are given an array of points on the X-Y plane points where points[i] = [x_i, y_i]. The points form a polygon when joined sequentially.
Return true if this polygon is convex and false otherwise.
You may assume the polygon formed by given points is always a simple polygon. In other words, we ensure that exactly two edges intersect at each vertex and that edges otherwise don't intersect each other.
Example 1:

Input: points = [[0,0],[0,5],[5,5],[5,0]]
Output: true
Example 2:

Input: points = [[0,0],[0,10],[10,10],[10,0],[5,5]]
Output: false
Constraints:
3 <= points.length <= 10^4points[i].length == 2-10^4 <= x_i, y_i <= 10^4- All the given points are unique.
Solution
Approach: All Turns the Same Way
Walk around the polygon. At every vertex the boundary turns either left or right. The polygon is convex exactly when it always turns the same way. A single turn the other way is a reflex corner, a dent like the point [5,5] in Example 2. (This only works because the polygon is guaranteed to be simple. A self-crossing star could turn one way all the time and still not be convex.)
The direction of the turn at b, going from a through b to c, is the sign of the cross product of the two edges:
cross = (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x)
A positive value is a left turn, a negative value is a right turn, and 0 means a, b and c lie on one line.
Check every vertex, with indices wrapping around (i, i + 1, i + 2 mod n), and remember the direction of the first real turn. If a later turn goes the other way, return false.
Two details need care:
- Collinear vertices. A cross product of
0is not a turn at all, so skip it and do not let it reset the direction. A square with extra points along its sides is still convex. - Overflow. One cross product fits in a 32-bit int (at most about 8 · 108), but the common trick of multiplying two of them to compare signs does not. The code compares signs directly, and Java and C++ compute the products in 64 bits to be safe.
Complexity: O(n) time and O(1) extra space.
class Solution:
def isConvex(self, points: List[List[int]]) -> bool:
n = len(points)
turn = 0 # direction of the turns so far: 1 = left, -1 = right, 0 = none seen yet
for i in range(n):
(ax, ay), (bx, by), (cx, cy) = points[i], points[(i + 1) % n], points[(i + 2) % n]
cross = (bx - ax) * (cy - by) - (by - ay) * (cx - bx) # > 0: a left turn at b
if cross != 0:
sign = 1 if cross > 0 else -1
if turn == -sign:
return False # turns both ways: a reflex corner
turn = sign
return True