3623. Count Number of Trapezoids I #2486
Answered
by
mah-shamim
mah-shamim
asked this question in
Q&A
-
Beta Was this translation helpful? Give feedback.
Answered by
mah-shamim
Dec 2, 2025
Replies: 1 comment 2 replies
-
|
We need to count horizontal trapezoids formed by 4 points where at least one pair of sides is horizontal (parallel to x-axis). Here's my PHP solution: Approach:
Let's implement this solution in PHP: 3623. Count Number of Trapezoids I <?php
/**
* @param Integer[][] $points
* @return Integer
*/
function countTrapezoids($points) {
$MOD = 1000000007;
// Group points by their y-coordinate
$yGroups = [];
foreach ($points as $point) {
$y = $point[1];
if (!isset($yGroups[$y])) {
$yGroups[$y] = 0;
}
$yGroups[$y]++;
}
// Count trapezoids using combinatorial approach
$result = 0;
// Convert group counts to array for processing
$counts = array_values($yGroups);
$n = count($counts);
// Method 1: Efficient O(n) approach using prefix sums
// For each group, we need to know sum of C(count_j, 2) for all j > i
// total = Σ_i Σ_j>i [C(count_i, 2) * C(count_j, 2)]
// Precompute C(count, 2) for each group
$combinations = [];
$totalCombinations = 0;
foreach ($counts as $count) {
if ($count >= 2) {
$c = (int)(($count * ($count - 1)) / 2);
$c %= $MOD;
$combinations[] = $c;
$totalCombinations = ($totalCombinations + $c) % $MOD;
} else {
$combinations[] = 0;
}
}
// Calculate result using efficient formula
// For each group i: result += combinations[i] * (sum of combinations[j] for j > i)
// We can compute this by maintaining a running sum from the end
$suffixSum = 0;
for ($i = $n - 1; $i >= 0; $i--) {
if ($combinations[$i] > 0) {
$result = ($result + ($combinations[$i] * $suffixSum) % $MOD) % $MOD;
$suffixSum = ($suffixSum + $combinations[$i]) % $MOD;
}
}
return $result % $MOD;
}
// Test cases
echo countTrapezoids([[1,0],[2,0],[3,0],[2,2],[3,2]]) . "\n"; // Output: 3
echo countTrapezoids([[0,0],[1,0],[0,1],[2,1]]) . "\n"; // Output: 1
?>Explanation:
Code Analysis
|
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
topugit
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment


We need to count horizontal trapezoids formed by 4 points where at least one pair of sides is horizontal (parallel to x-axis). Here's my PHP solution:
Approach:
kpoints, there areC(k, 2) = k*(k-1)/2ways to choose 2 points that could form a horizontal side.aandb, the number of trapezoids using points f…