[
math
geometry
]
Leetcode 0469. Convex Polygon
Problem statement
https://leetcode.com/problems/convex-polygon/
Solution
All we need to do is to make sure, that orientations of all triangles on 3
adjacent nodes are the same. To evaluate orientation of 3
points (x1; y1), (x2; y2), (x3; y3)
we need to evaluate (y2 - y1) * (x3 - x2) - (y3 - y2) * (x2 - x1)
.
Complexity
Time complexity is O(n)
, additional space is O(1)
.
Code
class Solution:
def isConvex(self, P):
def ccv(A, B, C):
return (B[1]-A[1]) * (C[0]-B[0]) - (C[1]-B[1]) * (B[0]-A[0])
ans = [ccv(A, B, C) for A, B, C in zip(P, P[1:]+P, P[2:]+P)]
return all(i >= 0 for i in ans) or all(i <= 0 for i in ans)