Normalize each domino by ordering its two values, count previous occurrences of that key, and add that count to the answer.
Complexity
O(n) time and O(1) space under the bounded domino values.
Count domino pairs equal either directly or after rotating one domino.
Normalize each domino by ordering its two values, count previous occurrences of that key, and add that count to the answer.
O(n) time and O(1) space under the bounded domino values.
package main
func numEquivDominoPairs(dominoes [][]int) int {
count := map[int]int{}
pairs := 0
for _, domino := range dominoes {
first, second := domino[0], domino[1]
if first > second {
first, second = second, first
}
key := first*10 + second
pairs += count[key]
count[key]++
}
return pairs
}
class Solution:
def numEquivDominoPairs(self, dominoes: list[list[int]]) -> int:
count: dict[tuple[int, int], int] = {}; pairs = 0
for first, second in dominoes:
key = (min(first, second), max(first, second)); pairs += count.get(key, 0); count[key] = count.get(key, 0) + 1
return pairs
function numEquivDominoPairs(dominoes: number[][]): number {
const count = new Map<number, number>(); let pairs = 0;
for (const [a, b] of dominoes) { const key = Math.min(a, b) * 10 + Math.max(a, b); pairs += count.get(key) ?? 0; count.set(key, (count.get(key) ?? 0) + 1); }
return pairs;
}