DryRun
AlgorithmsCourseCompare
DryRun
AlgorithmsCourseCompareGitHubLinkedIn

© 2026 DryRun. Built by Aditya Pandey.

AlgorithmsAdvancedConvex Hull (Graham Scan)
Advancedintermediategeometryconvex-hullstack

Convex Hull (Graham Scan)

Graham Scan sorts points by polar angle around a pivot, then uses a stack to keep only left turns. Points causing non-left turns are removed. Final stack forms the convex hull in counterclockwise order.

Complexity

Best
O(n log n)
Average
O(n log n)
Worst
O(n log n)
Space
O(n)

Implementation

struct P { long long x, y; };
long long cross(const P& a, const P& b, const P& c) {
    return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}
vector<P> convexHull(vector<P> pts) {
    sort(pts.begin(), pts.end(), [](const P& a, const P& b) {
        return a.x == b.x ? a.y < b.y : a.x < b.x;
    });
    vector<P> h;
    for (auto& p : pts) {
        while (h.size() >= 2 && cross(h[h.size()-2], h.back(), p) <= 0) h.pop_back();
        h.push_back(p);
    }
    int t = h.size() + 1;
    for (int i = (int)pts.size() - 2; i >= 0; i--) {
        while ((int)h.size() >= t && cross(h[h.size()-2], h.back(), pts[i]) <= 0) h.pop_back();
        h.push_back(pts[i]);
    }
    h.pop_back();
    return h;
}

How It Works

1.Turn Test

Cross product sign decides left-turn vs right-turn during hull construction.

2.Stack Maintenance

Pop while last turn is non-left; keep boundary points only.

3.Complexity

Sorting dominates runtime, giving O(n log n).

Related Algorithms

ArrowUpDownQuick SortSearchBinary Search

Test Your Knowledge

Quiz coming soon for this algorithm.

Back to all algorithms