1414. Triangles Around the Origin
A fountain sits at the origin of a plaza, and lamp posts stand at the positions in points, each [x, y]. Count the unordered triples of different indices whose triangle contains the fountain strictly inside, not on an edge and not at a vertex, and return the count as a long. Posts may share positions, and any triple that uses a post at the origin never counts.
Count the complement: a triple fails exactly when all three posts lie in some closed half-plane through the origin. Sort the non-origin posts by exact angle with cross products and use two pointers to count, for each post, the others within the following closed half-turn, taking care with posts on the same ray and on the opposite ray so no triple is counted twice. The intended solution runs in O(n log n) time and O(n) space.
Example 1
- Input:
- points = [[1,0],[-1,1],[-1,-1]]
- Output:
- 1
- Explanation:
The triangle has the origin strictly inside, so it counts.
Example 2
- Input:
- points = [[1,0],[-1,0],[0,1]]
- Output:
- 0
- Explanation:
The origin lies on the edge between (1, 0) and (-1, 0), so it is not strictly inside.
Example 3
- Input:
- points = [[0,0],[1,0],[0,1],[-1,-1]]
- Output:
- 1
- Explanation:
Only the triple (1, 0), (0, 1), (-1, -1) surrounds the origin; triples using the origin post never count.
Constraints
3 ≤ n ≤ 105
-104 ≤ x, y ≤ 104
The answer can exceed 32 bits.
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 10,000 msC++ 2,500 msJava 5,000 msJavaScript 5,000 msTypeScript 5,000 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)