Convex Polygon - 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.

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.

Note: A polygon is convex if all interior angles are less than 180 degrees, which means all cross products of consecutive edge vectors have the same sign.

Input & Output

Example 1 — Square (Convex)
$ Input: points = [[0,0],[0,1],[1,1],[1,0]]
Output: true
💡 Note: A square is convex. All interior angles are 90 degrees (less than 180), and all cross products have the same sign when traversed counterclockwise.
Example 2 — Concave Shape
$ Input: points = [[0,0],[0,10],[10,10],[10,0],[5,5]]
Output: false
💡 Note: This forms a concave polygon with an inward dent. The interior angle at [5,5] is greater than 180 degrees, making it non-convex.
Example 3 — Triangle (Convex)
$ Input: points = [[0,0],[3,0],[1,2]]
Output: true
💡 Note: Any triangle is always convex. All three interior angles are less than 180 degrees.

Constraints

  • 3 ≤ points.length ≤ 104
  • points[i].length == 2
  • -104 ≤ xi, yi ≤ 104
  • All the given points are unique

Visualization

Tap to expand
Convex Polygon Detection OverviewCONVEXAll cross products: + + + + +Result: trueCONCAVECross products: + + - + + +Result: falseAlgorithm Steps:1. Take 3 consecutive points2. Calculate cross product of edges3. Check if all signs match4. Return true if consistentCross Product Formula: (v1.x × v2.y) - (v1.y × v2.x)Time: O(n) | Space: O(1)
Understanding the Visualization
1
Input Points
Array of [x,y] coordinates forming a polygon
2
Cross Products
Calculate cross product for each consecutive triplet
3
Check Signs
All cross products must have consistent sign
Key Takeaway
🎯 Key Insight: A polygon is convex when all cross products have the same sign
Asked in
Google 12 Facebook 8 Amazon 6
28.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen