Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Sorting
  • MCQs on Sorting
  • Tutorial on Sorting
  • Bubble Sort
  • Quick Sort
  • Merge Sort
  • Insertion Sort
  • Selection Sort
  • Heap Sort
  • Sorting Complexities
  • Radix Sort
  • ShellSort
  • Counting Sort
  • Bucket Sort
  • TimSort
  • Bitonic Sort
  • Uses of Sorting Algorithm
Open In App
Next Article:
Quickhull Algorithm for Convex Hull
Next article icon

Convex Hull | Monotone chain algorithm

Last Updated : 11 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a set of points, the task is to find the convex hull of the given points. The convex hull is the smallest convex polygon that contains all the points. 
Please check this article first: Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping) 
 


Examples:

Input: Points[] = {{0, 3}, {2, 2}, {1, 1}, {2, 1}, {3, 0}, {0, 0}, {3, 3}} 
Output: 
(0, 0) 
(3, 0) 
(3, 3) 
(0, 3) 
 


 


Approach: Monotone chain algorithm constructs the convex hull in O(n * log(n)) time. We have to sort the points first and then calculate the upper and lower hulls in O(n) time. The points will be sorted with respect to x-coordinates (with respect to y-coordinates in case of a tie in x-coordinates), we will then find the left most point and then try to rotate in clockwise direction and find the next point and then repeat the step until we reach the rightmost point and then again rotate in the clockwise direction and find the lower hull.
Below is the implementation of the above approach:
 

CPP
// C++ implementation of the approach #include <bits/stdc++.h> #define llu long long int using namespace std;  struct Point {      llu x, y;      bool operator<(Point p)     {         return x < p.x || (x == p.x && y < p.y);     } };  // Cross product of two vectors OA and OB // returns positive for counter clockwise // turn and negative for clockwise turn llu cross_product(Point O, Point A, Point B) {     return (A.x - O.x) * (B.y - O.y)            - (A.y - O.y) * (B.x - O.x); }  // Returns a list of points on the convex hull // in counter-clockwise order vector<Point> convex_hull(vector<Point> A) {     int n = A.size(), k = 0;      if (n <= 3)         return A;      vector<Point> ans(2 * n);      // Sort points lexicographically     sort(A.begin(), A.end());      // Build lower hull     for (int i = 0; i < n; ++i) {          // If the point at K-1 position is not a part         // of hull as vector from ans[k-2] to ans[k-1]         // and ans[k-2] to A[i] has a clockwise turn         while (             k >= 2             && cross_product(ans[k - 2], ans[k - 1], A[i])                    <= 0)             k--;         ans[k++] = A[i];     }      // Build upper hull     for (size_t i = n - 1, t = k + 1; i > 0; --i) {          // If the point at K-1 position is not a part         // of hull as vector from ans[k-2] to ans[k-1]         // and ans[k-2] to A[i] has a clockwise turn         while (k >= t                && cross_product(ans[k - 2], ans[k - 1],                                 A[i - 1])                       <= 0)             k--;         ans[k++] = A[i - 1];     }      // Resize the array to desired size     ans.resize(k - 1);      return ans; }  // Driver code int main() {     vector<Point> points;      // Add points     points.push_back({ 0, 3 });     points.push_back({ 2, 2 });     points.push_back({ 1, 1 });     points.push_back({ 2, 1 });     points.push_back({ 3, 0 });     points.push_back({ 0, 0 });     points.push_back({ 3, 3 });      // Find the convex hull     vector<Point> ans = convex_hull(points);      // Print the convex hull     for (int i = 0; i < ans.size(); i++)         cout << "(" << ans[i].x << ", " << ans[i].y << ")"              << endl;      return 0; } 
Python3
class Point(object):     def __init__(self, x, y):         self.x = x         self.y = y  # A utility function to find next # to top in a stack   def nextToTop(S):     a = S.pop()     b = S.pop()     S.append(a)     return b  # A utility function to swap two # points   def swap(p1, p2):     return p2, p1  # A utility function to return # square of distance between # two points   def distSq(p1, p2):     return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)  # Prints convex hull of a set of n # points.   def convexHull(points, n):      # There must be at least 3 points     if (n < 3):         return      # Initialize Result     hull = []      # Find the leftmost point     l = 0     for i in range(1, n):         if (points[i].x < points[l].x):             l = i      # Start from leftmost point, keep     # moving counterclockwise until     # reach the start point again     # This loop runs O(h) times where h is     # number of points in result or output.     p = l     q = 0     while (True):          # Add current point to result         hull.append(points[p])          # Search for a point 'q' such that         # orientation(p, x, q) is counterclockwise         # for all points 'x'. The idea is to keep         # track of last visited most counterclock-         # wise point in q. If any point 'i' is more         # counterclock-wise than q, then update q.         q = (p + 1) % n          for i in range(0, n):              # If i is more counterclockwise than             # current q, then update q             if (orientation(points[p], points[i], points[q]) == 2):                 q = i          # Now q is the most counterclockwise with         # respect to p. Set p as q for next iteration,         # so that q is added to result 'hull'         p = q          # While we don't come to first point         if (p == l):             break      # Print Result     printHull(hull)  # A utility function to return square # of distance between p1 and p2   def distSq(p1, p2):     return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)  # To find orientation of ordered triplet (p, q, r). # The function returns following values # 0 --> p, q and r are collinear # 1 --> Clockwise # 2 --> Counterclockwise   def orientation(p, q, r):     val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)      if (val == 0):         return 0  # collinear     elif (val > 0):         return 1   # clock or wise     else:         return 2   # counterclock or wise  # Prints convex hull of a set of n points.   def printHull(hull):      print("The points in Convex Hull are:")     for i in range(len(hull)):         print("(", hull[i].x, ", ", hull[i].y, ")")   # Driver Code if __name__ == "__main__":      points = []     points.append(Point(0, 3))     points.append(Point(2, 2))     points.append(Point(1, 1))     points.append(Point(2, 1))     points.append(Point(3, 0))     points.append(Point(0, 0))     points.append(Point(3, 3))      n = len(points)     convexHull(points, n)      # This code is contributed by ishankhandelwals. 
JavaScript
// JS implementation of the approach function Point(x, y) {     this.x = x;     this.y = y; }  function crossProduct(O, A, B) {     return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x); }  function convexHull(A) {     let n = A.length;     let k = 0;      if (n <= 3)         return A;      let ans = new Array(2 * n);      // Sort points lexicographically     A.sort((a, b) => {         return a.x < b.x || (a.x == b.x && a.y < b.y);     });      // Build lower hull     for (let i = 0; i < n; ++i) {          // If the point at K-1 position is not a part         // of hull as vector from ans[k-2] to ans[k-1]          // and ans[k-2] to A[i] has a clockwise turn         while (k >= 2 && crossProduct(ans[k - 2], ans[k - 1], A[i]) <= 0)             k--;         ans[k++] = A[i];     }      // Build upper hull     for (let i = n - 1, t = k + 1; i > 0; --i) {          // If the point at K-1 position is not a part         // of hull as vector from ans[k-2] to ans[k-1]          // and ans[k-2] to A[i] has a clockwise turn         while (k >= t && crossProduct(ans[k - 2], ans[k - 1], A[i - 1]) <= 0)             k--;         ans[k++] = A[i - 1];     }      // Resize the array to desired size     ans.length = k - 1;      return ans; }  // Driver code let points = [];  // Add points points.push(new Point(0, 3)); points.push(new Point(2, 2)); points.push(new Point(1, 1)); points.push(new Point(2, 1)); points.push(new Point(3, 0)); points.push(new Point(0, 0)); points.push(new Point(3, 3));  // Find the convex hull let ans = convexHull(points);  // Print the convex hull for (let i = 0; i < ans.length; i++)     console.log("(" + ans[i].x + ", " + ans[i].y + ")");          // This code is contributed by ishankhandelwals. 
C#
using System; using System.Collections.Generic; using System.Collections; using System.Linq;  class Point {     public int x;     public int y;      public Point(int x, int y)     {         this.x = x;         this.y = y;     } }  class HelloWorld {      // A utility function to return square     // of distance between p1 and p2     public static int distSq(Point p1, Point p2)     {         return (p1.x - p2.x) * (p1.x - p2.x)             + (p1.y - p2.y) * (p1.y - p2.y);     }      // To find orientation of ordered triplet (p, q, r).     // The function returns following values     // 0 --> p, q and r are collinear     // 1 --> Clockwise     // 2 --> Counterclockwise     public static int orientation(Point p, Point q, Point r)     {         int val = (q.y - p.y) * (r.x - q.x)                   - (q.x - p.x) * (r.y - q.y);          if (val == 0)             return 0;         else if (val > 0)             return 1;         else             return 2;     }      // Prints convex hull of a set of n points.     public static void printHull(List<Point> hull)     {          Console.WriteLine("The points in Convex Hull are:");         for (int i = 0; i < hull.Count; i++) {             Console.WriteLine("(" + hull[i].x + ", "                               + hull[i].y + ")");         }     }      // Prints convex hull of a set of n     // points.     public static void convexHull(List<Point> points, int n)     {          // There must be at least 3 points         if (n < 3) {             return;         }          // Initialize Result         List<Point> hull = new List<Point>();          // Find the leftmost point         int l = 0;         for (int i = 1; i < n; i++) {             if (points[i].x < points[l].x) {                 l = i;             }         }          // Start from leftmost point, keep         // moving counterclockwise until         // reach the start point again         // This loop runs O(h) times where h is         // number of points in result or output.         int p = l;         int q = 0;         while (true) {              // Add current point to result             hull.Add(points[p]);              // Search for a point 'q' such that             // orientation(p, x, q) is counterclockwise             // for all points 'x'. The idea is to keep             // track of last visited most counterclock-             // wise point in q. If any point 'i' is more             // counterclock-wise than q, then update q.             q = (p + 1) % n;              for (int i = 0; i < n; i++) {                  // If i is more counterclockwise than                 // current q, then update q                 if (orientation(points[p], points[i],                                 points[q])                     == 2) {                     q = i;                 }             }              // Now q is the most counterclockwise with             // respect to p. Set p as q for next iteration,             // so that q is added to result 'hull'             p = q;              // While we don't come to first point             if (p == l) {                 break;             }         }          // Print Result         printHull(hull);     }      static void Main()     {         List<Point> points = new List<Point>();          points.Add(new Point(0, 3));         points.Add(new Point(2, 2));         points.Add(new Point(1, 1));         points.Add(new Point(2, 1));         points.Add(new Point(3, 0));         points.Add(new Point(0, 0));         points.Add(new Point(3, 3));          int n = points.Count;         convexHull(points, n);     } }  // The code is contributed by Nidhi goel. 
Java
import java.util.*;  class Point implements Comparable<Point> {     long x, y;      public Point(long x, long y)     {         this.x = x;         this.y = y;     }     // Implement compareTo method for sorting     @Override public int compareTo(Point p)     {         return Long.compare(x, p.x) != 0             ? Long.compare(x, p.x)             : Long.compare(y, p.y);     } }  public class ConvexHull {     // Cross product of two vectors OA and OB     // returns positive for counter clockwise     // turn and negative for clockwise turn     static long crossProduct(Point O, Point A, Point B)     {         return (A.x - O.x) * (B.y - O.y)             - (A.y - O.y) * (B.x - O.x);     }     // Returns a list of points on the convex hull     // in counter-clockwise order     static List<Point> convexHull(List<Point> A)     {         int n = A.size(), k = 0;          if (n <= 3)             return A;          List<Point> ans = new ArrayList<>(2 * n);          // Sort points lexicographically         Collections.sort(A);          // Build lower hull         for (int i = 0; i < n; ++i) {             // If the point at K-1 position is not a part             // of hull as vector from ans[k-2] to ans[k-1]             // and ans[k-2] to A[i] has a clockwise turn             while (k >= 2                    && crossProduct(ans.get(k - 2),                                    ans.get(k - 1), A.get(i))                           <= 0)                 ans.remove(--k);             ans.add(A.get(i));             k++;         }          // Build upper hull         for (int i = n - 2, t = k; i >= 0; --i) {              // If the point at K-1 position is not a part             // of hull as vector from ans[k-2] to ans[k-1]             // and ans[k-2] to A[i] has a clockwise turn             while (k > t                    && crossProduct(ans.get(k - 2),                                    ans.get(k - 1), A.get(i))                           <= 0)                 ans.remove(--k);             ans.add(A.get(i));             k++;         }          // Resize the array to desired size         ans.remove(ans.size() - 1);          return ans;     }      // Driver code     public static void main(String[] args)     {         List<Point> points = new ArrayList<>();          // Add points         points.add(new Point(0, 3));         points.add(new Point(2, 2));         points.add(new Point(1, 1));         points.add(new Point(2, 1));         points.add(new Point(3, 0));         points.add(new Point(0, 0));         points.add(new Point(3, 3));          // Find the convex hull         List<Point> ans = convexHull(points);          // Print the convex hull         for (Point p : ans)             System.out.println("(" + p.x + ", " + p.y                                + ")");     } } 

Output: 
(0, 0) (3, 0) (3, 3) (0, 3)

 

Next Article
Quickhull Algorithm for Convex Hull

A

andrew1234
Improve
Article Tags :
  • Sorting
  • Geometric
  • Competitive Programming
  • DSA
Practice Tags :
  • Geometric
  • Sorting

Similar Reads

    Convex Hull Algorithm
    The Convex Hull Algorithm is used to find the convex hull of a set of points in computational geometry. The convex hull is the smallest convex set that encloses all the points, forming a convex polygon. This algorithm is important in various applications such as image processing, route planning, and
    8 min read
    Convex Hull using Divide and Conquer Algorithm
    In computational geometry, a convex hull is the smallest convex polygon that contains a given set of points. It is a fundamental concept with applications in various fields such as computer graphics, robotics, and image processing. Importance of Convex Hull:Convex hulls are important in computationa
    15 min read
    Convex Hull using Jarvis' Algorithm or Wrapping
    Given a set of points in the plane. the convex hull of the set is the smallest convex polygon that contains all the points of it.We strongly recommend to see the following post first. How to check if two given line segments intersect?The idea of Jarvis's Algorithm is simple, we start from the leftmo
    13 min read
    Convex Hull using Graham Scan
    A convex hull is the smallest convex polygon that contains a given set of points. It is a useful concept in computational geometry and has applications in various fields such as computer graphics, image processing, and collision detection.A convex polygon is a polygon in which all interior angles ar
    15+ min read
    Convex Hull | Monotone chain algorithm
    Given a set of points, the task is to find the convex hull of the given points. The convex hull is the smallest convex polygon that contains all the points. Please check this article first: Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping) Examples: Input: Points[] = {{0, 3}, {2, 2}, {1, 1}, {2,
    11 min read
    Quickhull Algorithm for Convex Hull
    Given a set of points, a Convex hull is the smallest convex polygon containing all the given points. Input : points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}};Output : The points in convex hull are: (0, 0) (0, 3) (3, 1) (4, 4)Input : points[] = {{0, 3}, {1, 1}Output : Not P
    14 min read

    Problems on Convex Hull

    Dynamic Convex hull | Adding Points to an Existing Convex Hull
    Given a convex hull, we need to add a given number of points to the convex hull and print the convex hull after every point addition. The points should be in anti-clockwise order after addition of every point. Examples: Input : Convex Hull : (0, 0), (3, -1), (4, 5), (-1, 4) Point to add : (100, 100)
    15 min read
    Deleting points from Convex Hull
    Given a fixed set of points. We need to find convex hull of given set. We also need to find convex hull when a point is removed from the set. Example: Initial Set of Points: (-2, 8) (-1, 2) (0, 1) (1, 0) (-3, 0) (-1, -9) (2, -6) (3, 0) (5, 3) (2, 5) Initial convex hull:- (-2, 8) (-3, 0) (-1, -9) (2,
    15+ min read
    Perimeter of Convex hull for a given set of points
    Given n 2-D points points[], the task is to find the perimeter of the convex hull for the set of points. A convex hull for a set of points is the smallest convex polygon that contains all the points. Examples: Input: points[] = {{0, 3}, {2, 2}, {1, 1}, {2, 1}, {3, 0}, {0, 0}, {3, 3}} Output: 12 Inpu
    10 min read
    Check if the given point lies inside given N points of a Convex Polygon
    Given coordinates of the N points of a Convex Polygon. The task is to check if the given point (X, Y) lies inside the polygon. Examples:Input: N = 7, Points: {(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)}, Query: X = 3, Y = 2 Below is the image of plotting of the given points: Output: YES
    15 min read
    Tangents between two Convex Polygons
    Given two convex polygons, we aim to identify the lower and upper tangents connecting them. As shown in the figure below, TRL and TLR represent the upper and lower tangents, respectively. Examples: Input: First Polygon : [[2, 2], [3, 3], [5, 2], [4, 0], [3, 1]] Second Polygon : [[-1, 0], [0, 1], [1,
    15 min read
    Check if given polygon is a convex polygon or not
    Given a 2D array point[][] with each row of the form {X, Y}, representing the co-ordinates of a polygon in either clockwise or counterclockwise sequence, the task is to check if the polygon is a convex polygon or not. If found to be true, then print "Yes" . Otherwise, print "No".In a convex polygon,
    9 min read
    Check whether two convex regular polygon have same center or not
    Given two positive integers N and M which denotes the sides of the convex regular polygon where N < M, the task is to check whether polygons have the same center or not if N-sided polygon was inscribed in an M-sided polygon.Center of Polygon: Point inside a polygon which is equidistant from each
    3 min read
    Minimum Enclosing Circle
    Prerequisites: Equation of circle when three points on the circle are given, Convex HullGiven an array arr[][] containing N points in a 2-D plane with integer coordinates. The task is to find the centre and the radius of the minimum enclosing circle(MEC). A minimum enclosing circle is a circle in wh
    15+ min read
    How to Highlight Groups with Convex Hull in ggplot2 in R?
    In this article, we are going to see how to highlight groups with the convex hull in ggplot2 using R Programming Language.  Convex hull polygon refers to the draw a line bounding box around the outermost points in each group. Creating scatterplot for demonstration Here we will use the iris dataset t
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences