![]() |
VOOZH | about |
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 Input: points[] = {{0, 2}, {2, 1}, {3, 1}, {3, 7}} Output: 15.067
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. We will then find the perimeter of the convex hull using the points on the convex hull which can be done in O(n) time as the points are already sorted in clockwise order. Below is the implementation of the above approach:
12
Time Complexity : O(nlogn), where n is the number of points in the input vector.
Auxiliary Space Complexity : O(n), where n is the number of points in the input vector.