You are given a list of points in a 2D plane. Write a function to find the convex hull of these points. Please what is a convex hull, describe an algorithm to find the convex hull (e.g., Graham scan, Monotone Chain), write the code for one of these algorithms, and what is the time complexity of your solution.
Assistant
We are asked to do three things:
Define what a convex hull is.
Describe an algorithm to find the convex hull (either Graham scan or Monotone Chain).
Write the code for one of these algorithms and state the time complexity.
Let's structure the answer accordingly.
Step 1: Definition of Convex Hull
The convex hull of a set of points is the smallest convex polygon that contains all the points. Intuitively, it's the shape formed by a tight rubber band that encloses all the points.
Step 2: Choose an algorithm to describe and implement. Let's choose the Monotone Chain (also known as Andrew's algorithm) because it is simple and efficient, and it doesn't require sorting by angle (which Graham scan does) but only by x-coordinate (and then by y for ties). Also, it avoids the need for a separate orientation test for every point in the stack (like Graham scan does) but rather builds the lower and upper hulls separately.
Monotone Chain Algorithm:
Sort the points lexicographically (by x, then by y).
Build the lower hull:
Initialize an empty stack.
For each point in the sorted list:
While the stack has at least two points and the sequence of last two points in the stack and the current point makes a non-left turn (i.e., clockwise or collinear but we want to remove collinear points on the hull? Actually, for a strict convex hull we remove collinear points except the two endpoints? We'll have to decide. Typically, we remove points that are not making a left turn. So we pop until we get a left turn.
Push the current point.
Build the upper hull in a similar way by traversing the sorted list in reverse.
Concatenate the lower and upper hulls (removing the last point of each list to avoid duplication of the extreme points).
However, note that the Monotone Chain algorithm can also be implemented in a single pass by building both hulls in one loop? Actually, we build the lower hull from left to right and then the upper hull from right to left, and then combine.
Alternatively, we can build the lower hull and then the upper hull separately and then combine.
Let's describe the steps:
Step 1: Sort the points:
points.sort(key=lambda p: (p[0], p[1]))
Step 2: Build lower hull:
lower = []
for p in points:
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
Step 3: Build upper hull:
upper = []
for p in reversed(points):
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
Step 4: Combine: The entire hull is lower[:-1] + upper[:-1]
(because the first and last points of lower and upper are the same, so we remove the last point of each to avoid duplication).
Note: The cross product function:
cross(o, a, b) = (a[0]-o[0])(b[1]-o[1]) - (a[1]-o[1])(b[0]-o[0])
This computes the cross product of the vectors (a-o) and (b-o).
If cross > 0, then the turn is counterclockwise (left turn).
If cross < 0, then clockwise (right turn).
If cross == 0, then collinear.
In the while condition, we use <= 0 to remove points that are not strictly left turns (i.e., right turns and collinear). This will give us the convex hull without collinear points on the edges? Actually, if there are collinear points on the hull, we only keep the two extreme ones. This is the typical way to get the minimal convex hull (no three consecutive points are collinear). However, note that if we want to include all collinear points on the hull, we would change the condition to < 0 (only remove right turns, keep collinear). But the problem says "convex hull", and usually the convex hull is defined as the minimal convex polygon, so we don't want points on the edges unless they are vertices. So we remove collinear points in the middle.
But note: sometimes the problem might require including all points that lie on the convex hull. Then we would change the condition to < 0 (so collinear points are kept). However, the typical convex hull output is the set of vertices of the convex polygon. So we remove collinear points.
Let's stick with the condition <= 0 to remove non-left turns (including collinear). This gives the minimal set of vertices.
However, note that the Monotone Chain algorithm as described by Andrew uses the condition that for the lower hull we take points that are making a left turn, and similarly for the upper. But when we reverse for the upper hull, we are actually building the upper hull in the reverse order (from right to left) and we are also using the same condition (cross <= 0) which in the reversed order becomes the equivalent of a left turn in the original direction? Actually, in the reversed order, we are traversing from right to left, so the condition cross <= 0 in the reversed order means we are removing points that are making a right turn in the original left-to-right order? Let me clarify:
When we build the upper hull by going from rightmost to leftmost, we are effectively building the upper part of the hull. The condition cross <= 0 in that reversed traversal ensures that we are taking only left turns in the reversed direction, which corresponds to the upper hull being convex when viewed from above.
Alternatively, we can think of the entire hull as the lower hull (from leftmost to rightmost) and then the upper hull (from rightmost to leftmost) and we want both to be convex. The condition cross <= 0 in both loops is correct for building a convex polygon in the respective directions.
So the algorithm is:
def convex_hull(points):
# Sort the points lexicographically (by x then by y)
points = sorted(points)
if len(points) <= 1:
return points
code
# Build lower hull
lower = []
for p in points:
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
# Build upper hull
upper = []
for p in reversed(points):
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
# Concatenate the lower and upper hulls, removing the last point of each to avoid duplication.
return lower[:-1] + upper[:-1]
But note: what if there are less than 2 points? We handle that.
However, there is a caveat: if all points are collinear, then the convex hull is just the two endpoints. Our algorithm with condition <= 0 will remove all the inner collinear points and leave only the two endpoints? Let's test:
Lower hull:
Start: lower = []
Add (0,0) -> lower = [(0,0)]
Add (1,1) -> lower = [(0,0), (1,1)] (because we need at least 2 points to pop, so skip while)
Add (2,2):
cross((0,0),(1,1),(2,2)) = (1-0)(2-1) - (1-0)(2-0) = 11 - 12 = 1-2 = -1 <=0, so pop (1,1)
Now lower = [(0,0)]
Then we try again: we have only one point, so break and add (2,2) -> lower = [(0,0),(2,2)]
Then we combine: lower[:-1] = [(0,0)] and upper[:-1] = [(2,2)] -> result = [(0,0), (2,2)]
So we get the two endpoints. That's correct for the convex hull of collinear points.
However, note that the condition cross <= 0 removes points that are collinear and in between. So we are indeed getting the minimal set of vertices.
But what if we want to include all points that are on the convex hull (including those on the edges)? Then we would change the condition to < 0 in the while loops. But then for the collinear example, we would keep all three? Let's test:
Wait, that's the same? Because the cross product is negative (right turn) so we still pop. Actually, in the collinear case, the cross product is 0, so if we change to < 0, then we don't pop for cross=0. So let's test with cross=0:
For the example, the cross product of (0,0), (1,1), (2,2) is 0? Let's compute:
(1-0)(2-1) - (1-0)(2-0) = 11 - 12 = 1-2 = -1? Wait, that's not zero. Because the points are collinear? Actually, (0,0), (1,1), (2,2) are collinear. But the cross product formula:
code
cross(o, a, b) = (a.x - o.x)*(b.y - o.y) - (a.y - o.y)*(b.x - o.x)
For o=(0,0), a=(1,1), b=(2,2):
(1-0)*(2-0) - (1-0)*(2-0) = 1*2 - 1*2 = 2-2=0.
I made a mistake above: b.y - o.y = 2-0=2, and b.x - o.x=2-0=2. So indeed 0.
So with condition <= 0, we pop for cross=0. With condition < 0, we don't pop for cross=0.
Therefore, with condition < 0 in the while, we would keep (1,1) in the lower hull? Let's redo:
Lower hull with condition < 0:
Start: lower = []
(0,0) -> lower = [(0,0)]
(1,1) -> lower = [(0,0),(1,1)] (because we need at least 2 points to check the while, and we have only one, so skip)
(2,2): cross((0,0),(1,1),(2,2)) = 0 -> condition 0 < 0 is False, so we don't pop. Then we add (2,2) -> lower = [(0,0),(1,1),(2,2)]
Then combine: lower[:-1] = [(0,0),(1,1)] and upper[:-1] = [(2,2),(1,1)] -> result = [(0,0),(1,1),(2,2),(1,1)]? Wait, that has duplicate (1,1) and also note that we are concatenating and then we have (1,1) twice? Actually, the last point of lower is (2,2) and the first point of upper is (2,2) so when we take lower[:-1] and upper[:-1] we remove the last of lower and last of upper? Actually, we remove the last point of lower (which is (2,2)) and the last point of upper (which is (0,0))? That doesn't seem right.
Then lower[:-1] = [(0,0), (1,1)] and upper[:-1] = [(2,2), (1,1)]
So we get: [(0,0), (1,1), (2,2), (1,1)] -> which has (1,1) repeated and also the polygon is not closed correctly.
Actually, the typical way is to take lower and then upper without the first and last points of upper? Wait, the standard Monotone Chain algorithm:
code
hull = lower[:-1] + upper[:-1]
This works when we have the condition that the first and last points of lower and upper are the same? But in our example, the first point of lower is (0,0) and the last point of lower is (2,2). The first point of upper is (2,2) and the last point of upper is (0,0). So by taking lower without the last point and upper without the last point, we get:
code
lower: [ (0,0), (1,1) ] (removed (2,2))
upper: [ (2,2), (1,1) ] (removed (0,0))
Then the concatenation is [ (0,0), (1,1), (2,2), (1,1) ] -> which is not a convex hull and has a duplicate.
The problem is that when all points are collinear, we don't want to include the middle points. But if we want to include all points on the hull (including collinear) then we should change the condition to <= 0? Actually, we want to remove only the points that are making a right turn, but keep collinear? That would be condition < 0. But then we have the issue of duplicate points in the combined hull.
Actually, the standard Monotone Chain algorithm for the convex hull (minimal vertices) uses condition <= 0 and then combines as:
code
return lower + upper[1:-1]
Why? Because the first point of upper is the same as the last point of lower, and the last point of upper is the same as the first point of lower. So we take the entire lower, then the upper without the first and last.
Actually, the typical code for Monotone Chain (from Wikipedia) is:
code
points = sorted(points)
if len(points) <= 1:
return points
# Build lower hull
lower = []
for p in points:
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
# Build upper hull
upper = []
for p in reversed(points):
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
# Concatenate lower and upper, removing the last point of each because it is the same as the first point of the other.
return lower + upper[1:-1]
This is the standard way. Why? Because the first point of upper is the same as the last point of lower, and the last point of upper is the same as the first point of lower. So we take the entire lower, then the upper without the first and last points.
Now test with condition <0 (to keep collinear) and the same collinear points:
code
lower = [(0,0),(1,1),(2,2)]
upper = [(2,2),(1,1),(0,0)]
Then lower + upper[1:-1] = [(0,0),(1,1),(2,2)] + [(1,1)] = [(0,0),(1,1),(2,2),(1,1)] -> duplicate (1,1) and not a convex polygon.
So if we want to keep all collinear points, we have to adjust the way we combine? Actually, if we keep all collinear points, then the hull would be the entire set of points that are on the convex hull, which for collinear points is the entire set. But then the convex hull is a line segment, and the vertices are the two endpoints and all the points in between are on the edge. So we should only have the two endpoints as vertices. So the condition <=0 is correct for the minimal convex hull.
However, sometimes the problem may require the convex hull to include all points that lie on the boundary (so the vertices of the convex polygon, but if there are collinear points on an edge, we only want the two extreme points of that edge). That is exactly what condition <=0 does.
Therefore, we stick with condition <=0 and the combination lower + upper[1:-1].
But wait, what about a single point? We already handled len(points)<=1.
Now, what about two points?
points = [(0,0),(1,0)]
lower:
(0,0) -> lower=[(0,0)]
(1,0): while condition: len(lower)==1 -> skip, then append -> lower=[(0,0),(1,0)]
upper:
reversed: (1,0),(0,0)
(1,0) -> upper=[(1,0)]
(0,0): while condition: len(upper)==1 -> skip, then append -> upper=[(1,0),(0,0)]
Then return lower + upper[1:-1] = [(0,0),(1,0)] + [ ] = [(0,0),(1,0)] -> correct.
So the algorithm is:
Step 1: Sort the points.
Step 2: Build lower and upper with cross <= 0.
Step 3: Return lower + upper[1:-1]
However, note that if there are duplicate points? We should remove duplicates? The problem doesn't specify. Typically, we assume distinct points. But if there are duplicates, we might want to remove them to avoid having the same point multiple times. We can do:
code
points = sorted(set(points)) but points are lists? We are given a list of points, each point is a tuple or list? Let's assume we get a list of tuples or lists. We can convert to tuple and set? But then we lose order? Actually, we sort anyway. So we can do:
points = sorted(set(points)) if points are hashable (like tuples). But if they are lists, we can convert to tuple.
But the problem doesn't specify. Let's assume the input is a list of points, each point is a tuple (x,y). Then we can do:
code
points = sorted(set(points))
However, the problem might have duplicate points and we want to treat them as one. So we remove duplicates.
But if we are not allowed to change the input? We can work on a copy and remove duplicates.
Let's write the code accordingly.
We'll write a helper function for cross product.
Time complexity:
Sorting: O(n log n)
Building the hull: each point is pushed and popped at most once, so O(n)
Overall: O(n log n)
Let's code accordingly.
We'll write:
code
def convex_hull(points):
# Remove duplicates and sort
points = sorted(set(points))
if len(points) <= 1:
return points
def cross(o, a, b):
return (a[0]-o[0])*(b[1]-o[1]) - (a[1]-o[1])*(b[0]-o[0])
lower = []
for p in points:
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
upper = []
for p in reversed(points):
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
return lower + upper[1:-1]
However, note: what if the convex hull has only one point? We already handled that with the if at the beginning.
But what about two points? It works.
Let's test with a simple set:
code
points = [(0,0), (0,1), (1,0), (1,1)]
Sorted: [(0,0), (0,1), (1,0), (1,1)]
Lower:
(0,0) -> lower=[(0,0)]
(0,1):
while: len(lower)==1 -> skip, then append -> lower=[(0,0),(0,1)]
(1,0):
cross((0,0),(0,1),(1,0)) = (0-0)*(0-1) - (1-0)*(1-0) = 0 - 1*1 = -1 <=0 -> pop (0,1)
now lower=[(0,0)]
then append (1,0) -> lower=[(0,0),(1,0)]
(1,1):
cross((0,0),(1,0),(1,1)) = (1-0)*(1-0) - (0-0)*(1-0) = 1*1 - 0 = 1 >0 -> don't pop, then append -> lower=[(0,0),(1,0),(1,1)]
Upper:
reversed: (1,1), (1,0), (0,1), (0,0)
(1,1) -> upper=[(1,1)]
(1,0):
while: len(upper)==1 -> skip, append -> upper=[(1,1),(1,0)]
(0,1):
cross((1,1),(1,0),(0,1)) = (1-1)*(0-1) - (0-1)*(0-1) = 0 - (-1)*(-1) = 0 - 1 = -1 <=0 -> pop (1,0)
now upper=[(1,1)]
then append (0,1) -> upper=[(1,1),(0,1)]
(0,0):
cross((1,1),(0,1),(0,0)) = (0-1)*(0-1) - (1-1)*(0-1) = (-1)*(-1) - 0 = 1 >0 -> don't pop, then append -> upper=[(1,1),(0,1),(0,0)]
Then result = lower + upper[1:-1] = [(0,0),(1,0),(1,1)] + [(0,1)] = [(0,0),(1,0),(1,1),(0,1)]
This is the correct convex hull (a square). But note that the order is not necessarily counterclockwise? Actually, the lower hull is from leftmost to rightmost along the bottom, and the upper hull is from rightmost to leftmost along the top. So the order we get is:
lower: (0,0) -> (1,0) -> (1,1)
upper[1:-1] = [ (0,1) ]
So the order is (0,0), (1,0), (1,1), (0,1) -> which is clockwise? Let's check the cross product of consecutive points:
But the convex hull can be in any order as long as it's a convex polygon. Typically, we want the vertices in counterclockwise order. Our algorithm returns the lower hull in increasing x and then the upper hull in decreasing x, so the order is:
Start at leftmost bottom, go to rightmost bottom, then to rightmost top, then to leftmost top, and back to leftmost bottom? Actually, we are not enclosing the leftmost bottom again because we removed the duplicate. So we have:
(0,0) -> (1,0) -> (1,1) -> (0,1)
This is counterclockwise? Let's compute the cross product of the first three points:
cross((0,0),(1,0),(1,1)) = (1-0)*(1-0) - (0-0)*(1-0) = 1*1 - 0 = 1 >0 -> left turn.
Then cross((1,0),(1,1),(0,1)) = (1-1)*(0-1) - (1-0)*(0-1) = 0 - 1*(-1) = 1 >0 -> left turn.
Then cross((1,1),(0,1),(0,0)) = (0-1)*(0-1) - (1-1)*(0-1) = (-1)*(-1) - 0 = 1 >0 -> left turn.
Then cross((0,1),(0,0),(1,0)) = (0-0)*(1-0) - (0-1)*(1-0) = 0 - (-1)*1 = 1 >0 -> left turn.
So it is counterclockwise? Actually, the last one is the edge from (0,1) to (0,0) and then to (1,0). That is a left turn? Let's compute:
o=(0,1), a=(0,0), b=(1,0)
(a.x-o.x)*(b.y-o.y) - (a.y-o.y)*(b.x-o.x) = (0-0)*(0-1) - (0-1)*(1-0) = 0 - (-1)*1 = 1 -> positive, left turn.
So the polygon is counterclockwise. Good.
Therefore, the algorithm works.
Step 3: Time complexity.
As stated, O(n log n) because of the sorting.
Now, we write the answer.
But note: the problem says "write a function to find the convex hull". We assume the input is a list of points, each point is a tuple (x,y). We return the convex hull as a list of points in counterclockwise order, starting from the leftmost point and then going around.
We have described the Monotone Chain algorithm.
Let's write the code accordingly.
However, note: the problem says "write the code for one of these algorithms". We chose Monotone Chain.
We'll write the code in Python.
One more thing: the cross product function: we defined it inside.
Let's write the complete function.
Also, note that the input might be a list of lists or tuples. We are using set to remove duplicates, which requires hashable points. So we assume the input points are tuples. If they are lists, we can convert to tuples in the set.
We can do:
code
points = [tuple(p) for p in points]
points = sorted(set(points))
But if the input is already tuples, then it's fine.
Alternatively, we can avoid converting to set if we don't care about duplicates? But duplicates can cause problems in the algorithm? Actually, if there are duplicate points, then when we sort, they will be adjacent. Then in the hull building, we might have two identical points in a row? That would be a problem because the cross product with two identical points? Let's see:
code
If we have two identical points, then when we have lower with two points and the second is the same as the first? Actually, if we have two identical points, then the cross product with the next point?
Example: points = [(0,0), (0,0), (1,0)]
After set: {(0,0), (1,0)} -> that's what we want.
So we remove duplicates.
Let's code accordingly.
We'll write:
code
def convex_hull(points):
# Convert to tuples if necessary and remove duplicates
points = [tuple(p) for p in points]
points = sorted(set(points))
n = len(points)
if n <= 1:
return points
def cross(o, a, b):
return (a[0]-o[0])*(b[1]-o[1]) - (a[1]-o[1])*(b[0]-o[0])
lower = []
for p in points:
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
upper = []
for p in reversed(points):
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
# Remove the first and last of upper because they are the same as the last and first of lower.
return lower + upper[1:-1]
However, note: what if the convex hull has only two points? Then upper[1:-1] would be empty and we return lower (which has two points). That's correct.
What if the convex hull has three points? Then lower might have three points and upper might have three points, but the combination lower + upper[1:-1] would give 3 + (3-2) = 4? Wait, if the hull is a triangle, then:
code
Example: points = [(0,0), (1,0), (0,1)]
Sorted: [(0,0), (0,1), (1,0)]
Lower:
(0,0) -> lower=[(0,0)]
(0,1): -> lower=[(0,0),(0,1)]
(1,0): cross((0,0),(0,1),(1,0)) = (0-0)*(0-1) - (1-0)*(1-0) = 0 - 1*1 = -1 <=0 -> pop (0,1)
then lower=[(0,0)]
then append (1,0) -> lower=[(0,0),(1,0)]
Upper:
reversed: (1,0), (0,1), (0,0)
(1,0) -> upper=[(1,0)]
(0,1): cross((1,0),(0,1),(0,0)) = (0-1)*(0-0) - (1-0)*(0-1) = (-1)*0 - 1*(-1) = 0 - (-1) = 1 >0 -> don't pop, then append -> upper=[(1,0),(0,1)]
(0,0): cross((1,0),(0,1),(0,0)) = (0-1)*(0-1) - (1-0)*(0-1) = (-1)*(-1) - 1*(-1) = 1 - (-1) = 2 >0 -> don't pop, then append -> upper=[(1,0),(0,1),(0,0)]
Then lower + upper[1:-1] = [(0,0),(1,0)] + [(0,1)] = [(0,0),(1,0),(0,1)]
That's the triangle, but note the order: (0,0) -> (1,0) -> (0,1). That is counterclockwise? Check:
cross((0,0),(1,0),(0,1)) = (1-0)*(1-0) - (0-0)*(0-0) = 1*1 - 0 = 1 >0 -> left turn.
Then cross((1,0),(0,1),(0,0)) = (0-1)*(0-0) - (1-0)*(0-1) = (-1)*0 - 1*(-1) = 1 >0 -> left turn.
Then cross((0,1),(0,0),(1,0)) = (0-0)*(1-0) - (0-1)*(1-0) = 0 - (-1)*1 = 1 >0 -> left turn.
So it is counterclockwise. But note that the triangle's vertices are (0,0), (1,0), (0,1). That is correct.
So the algorithm works.
But wait, in the example above, the point (0,1) is the second point in the sorted order? Actually, sorted by x then y: (0,0), (0,1), (1,0). So the lower hull only got (0,0) and (1,0). The upper hull got (1,0), (0,1), (0,0). Then we removed the first and last of upper, so we kept (0,1). So the hull is (0,0), (1,0), (0,1). That's correct.
However, note that the point (0,1) is the leftmost top? Actually, the leftmost point is (0,0) and (0,1) is also leftmost. The algorithm uses the leftmost point as the starting point for both lower and upper. But in the lower hull, we go from leftmost to rightmost, and in the upper hull we go from rightmost to leftmost. So the leftmost point is the first in lower and the last in upper. We remove the last of upper (which is the leftmost) and the last of lower (which is the rightmost). Then we combine.
So the code is correct.
Let's write the answer accordingly.
Step 4: Time complexity: O(n log n) due to sorting.
Now, we write the answer in the required format.
We are to write:
- Definition of convex hull.
- Description of the algorithm (Monotone Chain).
- Code for the algorithm.
- Time complexity.
We'll write:
Definition:
The convex hull of a set of points is the smallest convex polygon that contains all the points.
Algorithm (Monotone Chain):
1. Sort the points lexicographically (by x-coordinate, and by y-coordinate if x-coordinates are equal).
2. Remove duplicate points.
3. If there are less than 2 points, return the points.
4. Build the lower hull:
- Initialize an empty list for the lower hull.
- Iterate over the sorted points:
* While the lower hull has at least two points and the last three points (the two most recent in the lower hull and the current point) do not make a left turn (i.e., the cross product is non-positive), remove the last point from the lower hull.
* Append the current point to the lower hull.
5. Build the upper hull in a similar way, but iterating over the sorted points in reverse order.
6. Combine the lower and upper hulls by concatenating the lower hull with the upper hull, excluding the first and last points of the upper hull (to avoid duplication of the extreme points).
Code:
code
def convex_hull(points):
# Convert points to tuples and remove duplicates
points = [tuple(p) for p in points]
points = sorted(set(points))
n = len(points)
if n <= 1:
return points
def cross(o, a, b):
return (a[0]-o[0])*(b[1]-o[1]) - (a[1]-o[1])*(b[0]-o[0])
lower = []
for p in points:
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
upper = []
for p in reversed(points):
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
return lower + upper[1:-1]
Time Complexity: O(n log n) due to the sorting step. The hull construction steps are linear because each point is pushed and popped at most once.
That's the answer.
Convex Hull Definition
The convex hull of a set of points in the plane is the smallest convex polygon that contains all the points. Imagine stretching a rubber band around the outermost points—it will snap into the shape of the convex hull. It consists of the "boundary" points that form the convex shape enclosing all others.
Monotone Chain Algorithm (Andrew's Algorithm)
Idea:
Sort points lexicographically (by (x), then by (y)), then construct the lower and upper hulls separately by scanning in forward and reverse order, using a stack-like list to keep only points that make left turns (counterclockwise orientation). Finally, merge the two hulls (excluding duplicate endpoints).
Steps:
Sort all points lexicographically (first by (x), then by (y)).
Remove duplicates to avoid degenerate cases.
If (\leq 2) points, return them directly (they are their own convex hull).
Build lower hull:
Iterate through sorted points left to right. For each point (p):
While the last two points in the current hull and (p) form a non-left turn (cross product (\leq 0)), pop the last point.
Append (p).
Build upper hull:
Same as lower hull but iterate from right to left (reverse order).
Combine: Concatenate lower hull with upper hull excluding the first and last points of the upper hull (to avoid repeating the extreme points).
Cross product helper:
For points (o, a, b), compute:
[
\text{cross}(o, a, b) = (a_x - o_x)(b_y - o_y) - (a_y - o_y)(b_x - o_x)
]
(> 0): counterclockwise (left turn)
(< 0): clockwise (right turn)
(= 0): collinear
Python Implementation
python
def convex_hull(points):
"""
Compute the convex hull of a set of 2D points using the Monotone Chain algorithm.
Args:
points: List of points, each point is (x, y) (tuple or list of numbers).
Returns:
List of points on the convex hull in counterclockwise order, starting from the leftmost point.
"""
# Convert to tuples and remove duplicates
pts = [tuple(p) for p in points]
pts = sorted(set(pts))
n = len(pts)
if n <= 1:
return pts
def cross(o, a, b):
"""Cross product of OA and OB vectors, i.e., z-component of (a-o) x (b-o)."""
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
# Build lower hull
lower = []
for p in pts:
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
# Build upper hull
upper = []
for p in reversed(pts):
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
# Concatenate lower and upper, removing duplicate endpoints
return lower + upper[1:-1]
Time Complexity
Sorting: (O(n \log n)) (dominant step).
Hull construction: Each point is pushed and popped at most once from each hull list → (O(n)).
Overall: (O(n \log n)).
Note: The algorithm is output-sensitive in the sense that if the hull has (h) points, the construction loops run in (O(n)) time after sorting. But sorting remains the bottleneck.
This implementation returns the convex hull vertices in counterclockwise order, starting from the leftmost point (and if multiple leftmost, the bottommost among them).