Count Number of Trapezoids I Problem
Description
LeetCode Problem 3623.
You are given a 2D integer array points, where points[i] = [x_i, y_i] represents the coordinates of the i^th 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 10^9 + 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 <= 10^5–10^8 <= x_i, y_i <= 10^8- All points are pairwise distinct.
Solution
Approach: Counting Horizontal Segments
A horizontal trapezoid needs two horizontal sides on different rows, so group the points by y and count v points per row. Choosing two points on a row gives t = v(v - 1) / 2 possible horizontal segments. A trapezoid is one segment from one row paired with one segment from a different row, and every such pair gives a distinct trapezoid.
Process the rows one by one while keeping s, the number of segments in all earlier rows. For each row add s * t to the answer, then add t to s. Take everything modulo 10^9 + 7.
Complexity: O(n) time and O(n) space.
class Solution:
def countTrapezoids(self, points: List[List[int]]) -> int:
mod = 10**9 + 7
cnt = Counter(p[1] for p in points)
ans = s = 0
for v in cnt.values():
t = v * (v - 1) // 2
ans = (ans + s * t) % mod
s += t
return ans