You are given an array points of points on the X-Y plane, 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 the given points is always a simple polygon. In other words, exactly two edges meet at each vertex, and edges otherwise don't intersect each other.
Function Signature
def is_convex(points: list[list[int]]) -> bool:
Rules
-
The edges are
points[0]
to
points[1]
,
points[1]
to
points[2]
, and so on, plus the closing edge from
points[n - 1]
back to
points[0]
.
-
The vertices may be listed clockwise or counterclockwise.
-
Three consecutive collinear vertices (an interior angle of exactly 180 degrees) do not make the polygon non-convex.
Constraints
-
3 <= len(points) <= 10^4
-
-10^4 <= x_i, y_i <= 10^4
-
All the given points are unique.
-
The points always form a simple polygon.
Examples
Input: points = [[0,0],[0,5],[5,5],[5,0]]
Output: True
The four points form an axis-aligned 5 by 5 square, traversed clockwise. Every turn is a right turn, so the polygon is convex.
Input: points = [[0,0],[0,10],[10,10],[10,0],[5,5]]
Output: False
The boundary runs up the left side of a 10 by 10 square, across the top and down the right side, then goes in from (10,0) to (5,5) and back out to (0,0). There is no bottom edge: the vertex (5,5) is a dent pointing into the square, and the boundary turns the opposite way there.
Input: points = [[0,0],[2,0],[4,0],[4,3],[0,3]]
Output: True
This is a 4 by 3 rectangle with an extra vertex at (2,0) in the middle of the bottom edge. The straight-through vertex is allowed, and every other turn is a left turn.