Convex Polygon — LeetCode 469 Python Solution

MediumLeetCode PremiumGeometryArrayMath
Problem
#469
Reading time
3 min

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 True

Complexity

MeasureComplexity
TimeO(n) or O(1)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview