Find the Number of Ways to Place People I Problem
Description
LeetCode Problem 3025.
You are given a 2D array points of size n x 2 representing integer coordinates of some points on a 2D plane, where points[i] = [x_i, y_i].
Count the number of pairs of points (A, B), where
Ais on the upper left side ofB, and- there are no other points in the rectangle (or line) they make (including the border), except for the points
AandB.
Return the count.
Example 1:
Input: points = [[1,1],[2,2],[3,3]]
Output: 0
Explanation:

There is no way to choose A and B such that A is on the upper left side of B.
Example 2:
Input: points = [[6,2],[4,4],[2,6]]
Output: 2
Explanation:

- The left one is the pair (points[1], points[0]), where points[1] is on the upper left side of points[0] and the rectangle is empty.
- The middle one is the pair (points[2], points[1]), same as the left one it is a valid pair.
- The right one is the pair (points[2], points[0]), where points[2] is on the upper left side of points[0], but points[1] is inside the rectangle so it's not a valid pair.
Example 3:
Input: points = [[3,1],[1,3],[1,1]]
Output: 2
Explanation:

- The left one is the pair (points[2], points[0]), where points[2] is on the upper left side of points[0] and there are no other points on the line they form. Note that it is a valid state when the two points form a line.
- The middle one is the pair (points[1], points[2]), it is a valid pair same as the left one.
- The right one is the pair (points[1], points[0]), it is not a valid pair as points[2] is on the border of the rectangle.
Constraints:
2 <= n <= 50points[i].length == 20 <= points[i][0], points[i][1] <= 50- All
points[i]are distinct.
Solution
Approach: Sorting and Enumeration
Fix the upper-left person (x1, y1). Another person (x2, y2) can be the lower-right one only if nobody else is inside or on the border of the rectangle they span.
Sort the points by x ascending, and by y descending when x ties. Then every point after i in this order has x2 >= x1. For each i, scan the later points and keep maxY, the largest y among the lower-right partners accepted so far. A point is a valid partner when maxY < y2 <= y1: it is not above the upper-left point, and no earlier accepted point sits inside the rectangle. Count it and set maxY = y2.
Complexity: time O(n^2), space O(log n) for the sort, where n is the number of points.
from math import inf
class Solution:
def numberOfPairs(self, points: List[List[int]]) -> int:
points.sort(key=lambda x: (x[0], -x[1]))
ans = 0
for i, (_, y1) in enumerate(points):
max_y = -inf
for _, y2 in points[i + 1 :]:
if max_y < y2 <= y1:
max_y = y2
ans += 1
return ans