Convex Hull Algorithm - Problem

Given a set of 2D points in the plane, find the convex hull of these points. The convex hull is the smallest convex polygon that contains all the given points.

A convex hull can be visualized as the shape formed by stretching a rubber band around all the points - the band will touch some points (which form the hull) and enclose all others.

Return the points that form the convex hull in counter-clockwise order, starting from the bottommost point (or leftmost if there are ties).

Input: An array of points where each point is represented as [x, y]

Output: Array of points forming the convex hull in counter-clockwise order

Input & Output

Example 1 — Basic Square with Interior Point
$ Input: points = [[1,1],[2,2],[2,0],[0,0],[1,0]]
Output: [[0,0],[2,0],[2,2],[1,1]]
💡 Note: The convex hull excludes the interior point (1,0) and forms a quadrilateral with vertices at (0,0), (2,0), (2,2), and (1,1) in counter-clockwise order
Example 2 — Triangle
$ Input: points = [[0,3],[1,1],[2,2],[4,4],[0,0],[1,2],[3,1],[3,3]]
Output: [[0,0],[4,4],[0,3]]
💡 Note: After removing interior points, the convex hull is a triangle with vertices (0,0), (4,4), (0,3)
Example 3 — All Points Collinear
$ Input: points = [[1,1],[2,2],[3,3]]
Output: [[1,1],[3,3]]
💡 Note: When all points lie on a line, the convex hull consists of just the two endpoints

Constraints

  • 1 ≤ points.length ≤ 3000
  • -50 ≤ points[i][0] ≤ 50
  • -50 ≤ points[i][1] ≤ 50
  • All points are unique

Visualization

Tap to expand
INPUT POINTSALGORITHM STEPSCONVEX HULL(0,0)(1,1)(2,0)(2,2)(1,3)8 scattered pointsincluding interior points1Sort by x-coordinate2Build lower hull chain3Build upper hull chain4Combine chainsMaintain left turns onlyBacktrack on right turns(0,0)(2,0)(2,2)(1,1)4 hull verticesCounter-clockwise orderKey Insight:Sort points lexicographically, then build upper and lower chains by maintainingleft turns only - backtrack whenever you would make a right turn.TutorialsPoint - Convex Hull Algorithm | Andrew's Monotone Chain
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
23.4K Views
Medium Frequency
~35 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