1411. Half-Plane Max

Hard7.5 points estimatedGeometrySortingTwo Pointers

A lighthouse stands at the origin of a flat map, and its beam sweeps one side of a straight line through the origin. You are given landmark positions points, each [x, y]. Choose a line through the origin and one closed side of it (landmarks exactly on the line count as lit), and return the maximum number of landmarks that can be lit. A landmark at the origin is always lit.

Several landmarks can share a position or lie on the same ray. Sort the landmarks away from the origin by exact angle using cross products, then sweep a two-pointer window that covers the closed half-turn starting at each landmark, taking care with landmarks on the same ray and on the exactly opposite ray. The intended solution runs in O(n log n) time and O(n) space.

Example 1

Input:
points = [[1,0],[-1,0],[0,1],[0,-1],[0,0]]
Output:
4
Explanation:

The closed half-plane y >= 0 holds the origin, (1, 0), (-1, 0) and (0, 1), which is four landmarks.

Example 2

Input:
points = [[3,3],[-3,-3],[0,0]]
Output:
3
Explanation:

A line through the origin and (3, 3) also contains (-3, -3), so all three are lit.

Example 3

Input:
points = [[1,1],[2,2],[1,-1],[-1,1],[-1,-1]]
Output:
4
Explanation:

The points span more than a half-turn, so at most four of the five fit in one closed half-plane.

Constraints

1 ≤ n ≤ 105

-104 ≤ x, y ≤ 104

Points may repeat and may be at the origin.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 8,800 msC++ 2,200 msJava 4,400 msJavaScript 4,400 msTypeScript 4,400 ms

Expected complexity

Time
O(n log n)
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…