Description
You are given a 2D integer array points
, where points[i] = [xi, yi]
represents the coordinates of the ith
point on the Cartesian plane.
A horizontal trapezoid is a convex quadrilateral with at least one pair of horizontal sides (i.e. parallel to the x-axis). Two lines are parallel if and only if they have the same slope.
Return the number of unique horizontal trapezoids that can be formed by choosing any four distinct points from points
.
Since the answer may be very large, return it modulo 109 + 7
.
Β
Example 1:
Input: points = [[1,0],[2,0],[3,0],[2,2],[3,2]]
Output: 3
Explanation:
There are three distinct ways to pick four points that form a horizontal trapezoid:
- Using points
[1,0]
,[2,0]
,[3,2]
, and[2,2]
. - Using points
[2,0]
,[3,0]
,[3,2]
, and[2,2]
. - Using points
[1,0]
,[3,0]
,[3,2]
, and[2,2]
.
Example 2:
Input: points = [[0,0],[1,0],[0,1],[2,1]]
Output: 1
Explanation:
There is only one horizontal trapezoid that can be formed.
Β
Constraints:
4 <= points.length <= 105
β108 <= xi, yi <= 108
- All points are pairwise distinct.
Solution
Python3
class Solution:
def countTrapezoids(self, points: List[List[int]]) -> int:
MOD = 10 ** 9 + 7
y_count = defaultdict(int)
# Count how many points lie on each y-level
for x, y in points:
y_count[y] += 1
curr = res = 0
for v in y_count.values():
lines = v * (v - 1) // 2
res = (res + curr * lines) % MOD
curr = (curr + lines) % MOD
return res