Recently I came across the problem of finding the convex hull of a set of 2D points and how it can be solved using a divide and conquer algorithm. In this article I’m going to share the implementation details of the algorithm, what challenges I found and a demo where you can see how it works step by step.
Introduction
Given a set of points in a two-dimensional plane, the convex hull is a convex polygon formed by a subset of the points that contains all the points. You can think about it as a cord stretched around a couple of pins, pinned on a board. Finding the convex hull is useful in many domains, from mathematics to quantum physics, and many algorithms have been developed over the years to solve this problem (Graham scan, Quickhull, Andrew’s algorithm, Chan’s algorithm, just to name a few). Most of these algorithms have O(n * log(n)) runtime, and so does the Divide and Conquer one, which I first heard about in a lecture from [MIT].
A few weeks after watching the video, I implemented it in Go as part of a coding challenge for an interview. As I was pretty happy with how the algorithm worked, I decided to share it here. Here is what it looks like:
The algorithm
Before describing the steps of the algorithm, let’s take a look at what is the input and the expected output. We are given a list of 2D points, and we want to return a subset of these points, describing the convex hull that includes all the points from the input.
As all the Divide and Conquer algorithms, this one also has three main steps:
- Decompose the problem in sub-problems
- Solve the sub-problems
- Combine the results of the sub-problems
We want to decompose our plane in two half-planes, then calculate the convex hull for the points on each half-plane, and in the end, combine the convex hulls into one.
The decomposition can be done using a line with any orientation, and for simplicity we can use a vertical one. For this, we need to sort our points first, using their X-coordinate. It’s important to do the sorting as a preliminary step before the recursive function is called. Since the whole algorithm has O(n * log(n)) complexity, sorting the array of points (which is also O(n * log(n))) before we start computing the convex hull, is not going to affect our overall runtime.
Once we have our points sorted, we can start the main part of the algorithm. First, we just verify the length of the input: if there is only one point in the input array, we can return it; if there are more, we can split the array in half. We have now two arrays with equal lengths, with one containing the “left” points and the other the “right” points.
The next step is computing the convex hulls of the left and right side, and finally we can combine them. Combining is obviously the trickiest part, so let’s see how that works.
A naīve approach would be checking all the possible lines defined by the points from the plane, but that’s not optimal and there would be no point in using Divide and Conquer, as we are not taking any advantage from having the solutions of two sub-problems already.
If we have a look at the two polygons we want to merge, it’s easy to see that our task is to find the upper and lower lines that connect the two polygons and also make them convex. We can think about an easy solution here: just connect the topmost point from the left side to the topmost one from the right side to get the upper tangent, and then do the same with bottommost points to get the lower tangent. This is unfortunately not correct though, as there would be cases when some points would be left out from the resulting polygon.
The solution is the so called “two finger algorithm”: starting with the points closest to the vertical line delimiting the two polygons, start moving clockwise on the right side and counter-clockwise on the left side until we reach the pair of points for which the line they define intersects the delimiter at the highest point. This line will be the upper tangent. To get the lower one, apply the same steps, but this time go clockwise on the left on counter-clockwise on the right. This sounds complicated, so let’s visualize it to make it more understandable. On the following canvas just click to add points on the left and right sides. You will see both the left and right convex hulls, and using the “Step” button you can see the steps taken by the algorithm to determine the lower tangent of the merged hull.
Moving clockwise along points sounds simple, but how do we actually implement it? Well, we just need to make sure the convex hull algorithm is returning the array of points ordered this way. Which is easy to do: we have now the two polygons and the upper and lower tangents; start with the upper tangent, and just walk through the points from the right polygon until we reach the point that is also part of the lower tangent.
Then walk to the left side, and go through the points again until we reach the starting point of the upper tangent. At this point we have a “circle” - and the result is the convex hull we wanted to compute!
It’s easy to see that the algorithm has O(n * log(n)) runtime. In each iteration of the recursive function we are splitting the array in two (O(1)), then do the recursion on the two sides, and in the end combine the points (O(n)).
Challenges
During the implementation of this algorithm, I encountered some tricky parts that are worth mentioning, since they are not always brought up in other implementations.
First of all, the two-finger algorithm starts with the points closest to the delimiter line that splits the plane vertically. Finding these points is not trivial though. The algorithm returns the points of the convex hull in clockwise order, and in most of the cases, the left-/rightmost points will not be at the beginning or end of this array. This means we need to find these points, which results in iterating through the left and right polygons before we start computing the upper and lower tangents. This is an O(n) operation, which is OK in this case as the tangent searching part is also O(n). But it definitely adds something to the running time, which is not very nice. Probably another solution to this would be extending the data structure returned by the algorithm, so that besides the convex hull it would also return the left and rightmost points of it. These could be calculated during the merging process and probably it would reduce the runtime somewhat.
The second issue I noticed was also related to how the two-finger algorithm works. Since in the decomposition step we are simply splitting the points ordered by their X-coordinates in two equal parts, it can happen that the left and right sides both have points on the vertical line splitting the two sides. In this case, the algorithm can’t determine correctly the upper and lower tangents and the resulting polygon will be an incorrect one.
Demo
You can use this demo to play around with the algorithm to see how it works step by step. Just click on the canvas to add points, and when you are ready, click the “Step” button to step through the algorithm, or the “Solve” button to see the final result. When stepping through, the label in the top left indicates the step you are at:
- “Partition” means that the highlighted area is being split up in a left and right side (indicated by orange and blue points)
- “Convex hull” is shown when calculating the convex hulls for the left and right sides is finished
- and finally “Merge” shows the resulting convex hull after merging the left and right sides.
Code
The code used in this demo is available on Github. Feel free to reuse it and to provide me any feedback about it.
What’s next?
As next steps, I want to fix the issues I mentioned above, so that the algorithm will return correct results all the time and would also perform faster. Then I also want to see how the algorithm performs in comparison with other convex hull algorithms.
I hope you liked this article and found it useful. Feel free to send me an email with any feedback or suggestion you got, I would be more than happy to read it! Stay tuned for more articles like this :)