1405. Onion Layers

Hard7.5 points estimatedGeometrySortingMaths

Fence posts are planted at the positions in points, each [x, y]. A crew repeatedly stretches a rope around all posts still standing and pulls out every post that touches the rope, meaning every post on the boundary of the convex hull of the remaining posts, including posts lying in the middle of a hull edge and every copy of a post planted at a repeated position. Return how many rounds are needed until no post is left.

If the remaining posts are all on one line, or all at one location, they form the final round on their own. Compute the hull with the monotone chain while keeping collinear boundary points, remove everything on it, and repeat. The intended solution runs in O(n^2) time and O(n) space, since each round costs O(n) once the points are sorted.

Example 1

Input:
points = [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]
Output:
2
Explanation:

The eight boundary points of the 3 by 3 grid go first, then the centre (1, 1) forms the second round.

Example 2

Input:
points = [[0,0],[1,1],[2,2],[5,5]]
Output:
1
Explanation:

All points are collinear, so they form a single final round.

Example 3

Input:
points = [[1,1],[1,1],[1,1]]
Output:
1
Explanation:

All copies sit at one location, so one round removes them all.

Constraints

1 ≤ n ≤ 1000

-104 ≤ x, y ≤ 104

Points may repeat.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n^2)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…