Convex Polygon — LeetCode 469 Python Solution
MediumLeetCode PremiumGeometryArrayMath
- Problem
- #469
- Pattern
- Math and Number Theory
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given an array of points on the X-Y plane points where points[i] = [xi, yi]. The points form a polygon when joined sequentially.
Example
- Input
- points = [[0,0],[0,5],[5,5],[5,0]]
- Output
- true
Python solution
Python
class Solution:
def isConvex(self, points: List[List[int]]) -> bool:
n = len(points)
pre = cur = 0
for i in range(n):
x1 = points[(i + 1) % n][0] - points[i][0]
y1 = points[(i + 1) % n][1] - points[i][1]
x2 = points[(i + 2) % n][0] - points[i][0]
y2 = points[(i + 2) % n][1] - points[i][1]
cur = x1 * y2 - x2 * y1
if cur != 0:
if cur * pre < 0:
return False
pre = cur
return TrueComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) or O(1) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 469. Convex Polygon is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Geometry.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 469. Convex Polygon?
- LeetCode 469. Convex Polygon is rated Medium on LeetCode.
- What topics does LeetCode 469. Convex Polygon cover?
- LeetCode 469. Convex Polygon is tagged Geometry, Array and Math on LeetCode.
- Is LeetCode 469. Convex Polygon a premium problem?
- Yes. LeetCode 469. Convex Polygon is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.