To solve this, I realized that each domino can be uniquely represented by its sorted tuple form — for example, [2,1] becomes (1,2). This ensures that both [1,2] and [2,1] are considered equal. I then used a dictionary to count how many times each normalized domino appears. For each count greater than 1, I computed the number of unique pairs using the combination formula count * (count - 1) // 2, and summed these up to get the final answer.
class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
count = defaultdict(int)
res = 0
for a, b in dominoes:
key = tuple(sorted((a, b)))
res += count[key]
count[key] += 1
return res
- Time: O(n)
- Space: O(n)
