1399. Point in Polygon Classifier

Medium3.5 points estimatedGeometryMathsArray

A city planner has the outline of a protected park, a simple polygon with integer corners given in order in polygon as [x, y] pairs, and a list of building permits, each a point in queries. For every permit she needs to know where it falls relative to the park.

Return an array with one entry per query, in the same order: 2 if the point lies on the boundary (on an edge or at a corner), 1 if it lies strictly inside, and 0 if it lies outside. Decide inside versus outside with exact integer ray casting: count an edge only when exactly one of its endpoints is strictly above the query's y (a half-open rule) so that a ray passing through a vertex is not counted twice, and compare cross products instead of dividing. The polygon may be concave and may be listed in either direction. The intended solution runs in O(n) per query, so O(n * q) overall, with O(1) extra space beyond the output.

Example 1

Input:
polygon = [[0,0],[10,0],[10,10],[0,10]]queries = [[5,5],[10,5],[11,5],[0,0]]
Output:
[1,2,0,2]
Explanation:

(5,5) is inside, (10,5) is on the right edge, (11,5) is outside and (0,0) is a corner.

Example 2

Input:
polygon = [[0,0],[8,0],[8,8],[4,3],[0,8]]queries = [[4,5],[4,2],[1,5],[0,7]]
Output:
[0,1,1,2]
Explanation:

The dent above (4,3) is outside, so (4,5) gets 0; (4,2) and (1,5) are inside; (0,7) sits on the left edge.

Constraints

3 ≤ polygon.length ≤ 500

1 ≤ queries.length ≤ 200

-104 ≤ every coordinate ≤ 104

The polygon is simple and has non-zero area

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 * q)
Space
O(1)

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…