Given a list of dominoes where each domino is represented as a list of two integers [a, b], return the number of pairs (i, j) for which the two dominoes are equivalent. Two dominoes (a, b) and (c, d) are considered equivalent if, and only if, either (a == c and b == d) or (a == d and b == c).
Example:
Input: dominoes = [[1,2],[2,1],[3,4],[5,6]]
Output: 1
Explanation: The only equivalent pair is (0,1), because dominoes[0] is [1,2] and dominoes[1] is [2,1].
To solve this problem, we can follow these steps:
[2, 1]
will be represented as [1, 2]
.C(n, 2) = n * (n - 1) / 2
where n
is the count of that domino.Here’s how we can implement this in Python:
from collections import defaultdict
def numEquivDominoPairs(dominoes):
count_map = defaultdict(int)
# Normalize and count each domino occurrence
for domino in dominoes:
normalized = tuple(sorted(domino))
count_map[normalized] += 1
pairs = 0
# Calculate pairs
for count in count_map.values():
if count > 1:
pairs += (count * (count - 1)) // 2
return pairs
# Example usage
dominoes = [[1,2],[2,1],[3,4],[5,6]]
print(numEquivDominoPairs(dominoes)) # Output: 1
n
is the number of dominoes.n
keys (in the worst case where all dominoes are unique) resulting in O(n).Overall, the time complexity is O(n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?