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 INPUT X Y P0 P1 P2 P3 points array: [[0,0], [0,1], [1,1], [1,0]] Forms a unit square 4 vertices connected ALGORITHM STEPS 1 Get Edge Vectors v1 = P1-P0, v2 = P2-P1... 2 Compute Cross Products cross = v1.x*v2.y - v1.y*v2.x 3 Check Sign Consistency All same sign = convex 4 Return Result true if convex, false if not Cross Product Values: P0--P1--P2: cross = +1 P1--P2--P3: cross = +1 P2--P3--P0: cross = +1 P3--P0--P1: cross = +1 All positive - OK! FINAL RESULT 90 90 90 90 true CONVEX Verification: All angles = 90 deg All angles less than 180 Polygon is CONVEX Key Insight: Cross product of consecutive edge vectors determines turn direction. For a convex polygon, all turns must be in the same direction (all positive OR all negative cross products). Time: O(n) | Space: O(1) - single pass checking consecutive vertex triplets. TutorialsPoint - Convex Polygon | Optimized Cross Product Check
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