Maps app~40 min2s · 256 MBtarget O(n log n) time, O(n) spacemonotonic-stack
A city planner marks charging stations on a map, each at a pair of whole-number coordinates. The planner wants the shortest fence that keeps every station inside or on it.
The fence is a convex polygon. Its corners are stations, and a station that lies on the fence between two corners is not a corner. Your team lead asks: "How many corners does the fence have, and how big is the area inside?" A map can have 100,000 stations.
Write hull_corners_and_area(stations).
stations[i] = [x, y] is the position of a station. Two stations can share a position.Input: stations = [[0, 0], [4, 0], [2, 0], [4, 4], [0, 4], [2, 2], [1, 3]]
Output: [4, 32]The fence is the square from (0, 0) to (4, 4). The station (2, 0) lies on its bottom edge, so it is not a corner. The stations (2, 2) and (1, 3) are inside. The chains built from the sorted stations:
| Chain | Corner points kept at the end | What is dropped |
|---|---|---|
| Lower (left to right) | (0, 0), (4, 0), (4, 4) | (0, 4), (1, 3), (2, 0), (2, 2) were popped as they stopped being left turns |
| Upper (right to left) | (4, 4), (0, 4), (0, 0) | (4, 0), (2, 2), (2, 0), (1, 3) were popped |
The corners are (0, 0), (4, 0), (4, 4) and (0, 4): 4 corners. The square has area 16, so twice the area is 32.
Input: stations = [[3, 3]]
Output: [1, 0]One station is one corner, and the area is 0.
Input: stations = [[0, 0], [0, 2], [0, 4]]
Output: [2, 0]The stations lie on a line. The ends are the corners, and the middle station is on the fence between them.
1 ≤ len(stations) ≤ 100,000-1,000,000 ≤ x, y ≤ 1,000,000Testing every pair of stations as a fence edge means checking every other station, which is about 10^15 steps for 100,000 stations. The answer must come from sorting the stations once, then a single pass that keeps only the points that turn the right way.