1128. Number of Equivalent Domino Pairs #1642
-
Topics: Given a list of Return the number of pairs Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the number of equivalent domino pairs in a given list of dominoes. Two dominoes are considered equivalent if one can be rotated to match the other. We can efficiently count these pairs using a hash map to track the frequency of each standardized domino form. Approach
Let's implement this solution in PHP: 1128. Number of Equivalent Domino Pairs <?php
/**
* @param Integer[][] $dominoes
* @return Integer
*/
function numEquivDominoPairs($dominoes) {
$freq = array();
foreach ($dominoes as $d) {
$min = min($d[0], $d[1]);
$max = max($d[0], $d[1]);
$key = "$min,$max";
if (isset($freq[$key])) {
$freq[$key]++;
} else {
$freq[$key] = 1;
}
}
$total = 0;
foreach ($freq as $count) {
if ($count >= 2) {
$total += $count * ($count - 1) / 2;
}
}
return $total;
}
// Example 1
$dominoes1 = [[1,2],[2,1],[3,4],[5,6]];
echo numEquivDominoPairs($dominoes1) . "\n"; // Output: 1
// Example 2
$dominoes2 = [[1,2],[1,2],[1,1],[1,2],[2,2]];
echo numEquivDominoPairs($dominoes2) . "\n"; // Output: 3
?> Explanation:
This approach ensures we efficiently count the equivalent pairs in linear time, making it suitable for large input sizes as specified in the problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to determine the number of equivalent domino pairs in a given list of dominoes. Two dominoes are considered equivalent if one can be rotated to match the other. We can efficiently count these pairs using a hash map to track the frequency of each standardized domino form.
Approach
[a, b]
, we standardize its representation by sorting the elements such that the smaller element comes first. This transforms each domino into a key(min(a, b), max(a, b))
.c
, the number …