Parcel-delivery app~40 min2s · 256 MBtarget O((n + q) log n) time, O(1) spacebinary-search
A freight company serves a depot zone drawn on a map. The zone is a convex polygon whose corners are whole-number coordinates. Customers whose address is inside the zone get same-day delivery, and addresses on the border get a special rate.
Your team lead asks: "For each address, is it outside the zone, inside it, or on its border?" A zone can have 20,000 corners, and a day brings up to 100,000 addresses.
Write classify_addresses(zone, addresses).
zone lists the corners of a convex polygon in counter-clockwise order, starting at any corner. No three corners lie on a line, and no corner repeats.addresses[i] = [x, y] is the position of address i.0 when the address is outside the zone, 1 when it is strictly inside, and 2 when it is on the border.Input: zone = [[0, 0], [6, 0], [8, 4], [3, 7], [-1, 4]], addresses = [[3, 3], [3, 0], [9, 5], [0, 0], [7, 2], [-2, 2]]
Output: [1, 2, 0, 2, 2, 0]The zone is a pentagon. Each address is tested from the first corner (0, 0):
| Address | Test from the first corner | Result |
|---|---|---|
| (3, 3) | between the two edges at (0, 0); the binary search finds the wedge of corners (6, 0) and (8, 4); it is on the left of the far edge | 1 (inside) |
| (3, 0) | on the line from (0, 0) to (6, 0), between the two ends | 2 (border) |
| (9, 5) | between the two edges at (0, 0); the wedge is (8, 4) and (3, 7); it is to the right of the far edge | 0 (outside) |
| (0, 0) | the first corner itself | 2 (border) |
| (7, 2) | between the two edges; the wedge is (6, 0) and (8, 4); it is on the far edge | 2 (border) |
| (-2, 2) | to the left of the edge from (0, 0) to (-1, 4), so outside the angle | 0 (outside) |
Input: zone = [[0, 0], [4, 0], [0, 4]], addresses = [[1, 1]]
Output: [1]The point (1, 1) is inside the triangle.
Input: zone = [[0, 0], [4, 0], [0, 4]], addresses = [[5, 0], [2, 2]]
Output: [0, 2]The point (5, 0) is on the line of the bottom edge but beyond its end, so it is outside. The point (2, 2) is on the long edge.
3 ≤ len(zone) ≤ 20,000, and the zone is a strictly convex polygon in counter-clockwise order1 ≤ len(addresses) ≤ 100,000-1,000,000 ≤ x, y ≤ 1,000,000Checking every edge for every address is 20,000 × 100,000 = 2 billion steps. That is too slow for 2 seconds. Convexity must be used, so that each address takes far fewer than 20,000 steps.