I'm currently focused on defining the "convex hull" precisely. This means I'm working to solidify my understanding of what the algorithm needs to achieve, and the formal properties of the shape it outputs. I'm considering different definitions, including the minimal convex polygon enclosing the points, and the intersection of all convex sets containing the points.
Visualizing the Concept
I'm now thinking about the "rubber band" analogy to make the concept more intuitive. This helps me grasp the idea that the convex hull is the smallest convex shape encompassing the points. Formally, I'm focusing on the mathematical definition: a subset of the original points forming a polygon that contains all other points, ensuring convexity.
Selecting the Best Algorithm
I've decided on Andrew's Monotone Chain algorithm. It offers a solid O(N log N) time complexity and is robust enough for general use, especially for implementation. I like it better than Graham Scan due to the ease of sorting and the symmetrical logic for upper and lower hulls, using the cross product to determine orientation. I'm focusing on outlining each step, from input and sorting to the core logic using the cross product, and the handling of edge cases like collinear points.
Understanding Turn Direction
My current focus is nailing down the cross-product calculation. It's the core geometric primitive I need, and I'm diving deeper into what it precisely means for point triplets. I'm building it, thinking about counter-clockwise (left turns) and clockwise (right turns), zero representing collinearity. Understanding turn direction with that core formula will be crucial for the hulls.
Implementing the Algorithm
I'm now deep-diving into the algorithm's implementation using Andrew's Monotone Chain. The core challenge is the correct usage of the cross product for determining turn direction. The code structure is coming together, starting with sorting and building the lower and upper hulls. The key is in removing the duplicate endpoints. Analyzing the Python implementation shows the crucial loops and how turn-detection works within the algorithm. I'm focusing now on time and space complexity.
Defining Turn Direction
My current thinking is around the 2D cross product and what it truly signifies. It's essentially the z-component of a torque vector, which I'm now calling "Orientation". I need to make sure I clarify how duplicate points are handled as well. The time complexity is dominated by sorting, making the algorithm O(N log N). The loop itself is linear since each point is pushed and popped at most once.
The most standard, robust, and efficient algorithm for computing the convex hull in 2D space is Andrew’s Monotone Chain Algorithm.
It is a variation of the Graham Scan algorithm. It sorts the points lexicographically (by X, then Y) and constructs the upper and lower hulls of the polygon separately.
Mathematical Prerequisite: The Cross Product
To implement this algorithm, we need a helper function to determine the "turn" direction of three points (O,A,B). We use the 2D cross product formula:
CP=(Ax−O
CP>0: Counter-Clockwise turn (Left turn).
CP<0: Clockwise turn (Right turn).
CP=0: Collinear (Points lie on a straight line).
The Monotone Chain Algorithm
Steps:
Sort: Sort the set of points, P, primarily by x-coordinate and secondarily by y-coordinate.
Lower Hull: Iterate through the sorted list to build the lower hull. For every new point added, check if the last three points make a counter-clockwise turn. If they make a clockwise turn (or are collinear), delete the middle point and check again.
Upper Hull: Iterate through the sorted list in reverse order and perform the exact same logic to build the upper hull.
Concatenate: combine the two lists. Note that the first and last points will be duplicates, so remove one of them from the merge.
Python Implementation
Here is the implementation of the algorithm.
python
def get_convex_hull(points):
"""
Computes the convex hull of a set of 2D points.
Input: list of (x, y) tuples.
Output: list of vertices of the convex hull in counter-clockwise order.
"""
# A hull cannot usually be formed with fewer than 3 points
# (unless you consider a line or point a hull, in which case return points)
if len(points) <= 2:
return points
# 1. Sort the points by x-coordinate, then y-coordinate
# This allows us to process strictly from left to right
sorted_points = sorted(points)
# Helper function: Cross Product (2D)
# Returns:
# > 0 : Counter-Clockwise
# < 0 : Clockwise
# = 0 : Collinear
def cross_product(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
# 2. Build Lower Hull
lower = []
for p in sorted_points:
# If we have at least 2 points on the stack, check the turn.
# If the turn is Clockwise (<= 0), remove the last point because
# it makes the shape "concave" rather than convex.
while len(lower) >= 2 and cross_product(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
# 3. Build Upper Hull
# We iterate in reverse order (right to left)
upper = []
for p in reversed(sorted_points):
while len(upper) >= 2 and cross_product(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
# 4. Concatenate
# The last point of 'lower' is the first point of 'upper'.
# The last point of 'upper' is the first point of 'lower'.
# We remove the duplicates to get a clean polygon.
return lower[:-1] + upper[:-1]
# --- Example Usage ---
coords = [(0, 0), (1, 1), (2, 2), (4, 4), (0, 4), (4, 0), (2, 1), (1, 2)]
hull = get_convex_hull(coords)
print("Convex Hull Points:")
for p in hull:
print(p)
Complexity Analysis
Time Complexity: O(NlogN)
Sorting the points takes O(NlogN).
Building the lower and upper hulls involves iterating through the points linearly. Although there is a while loop inside the for loop, each point is "pushed" onto the stack once and "popped" at most once. This makes the hull construction O.
Why this approach?
There are other algorithms, such as Jarvis March (Gift Wrapping). However, Jarvis March has a complexity of O(N⋅H) (where H is the number of points on the hull).
If the hull is small, Jarvis March is fast.
If the hull contains all points (like a circle), Jarvis March becomes O(N2).
Monotone Chain guarantees O(NlogN) regardless of the shape of the data, making it safer for general-purpose use.
x
)
×
(By−
Oy)−
(Ay−
Oy)×
(Bx−
Ox)
(
N
)
Total: O(NlogN).
Space Complexity: O(N)
We need to store the sorted list of points and the output stack for the hull, which in the worst case (if all points are on the convex hull) is equal to the input size.