Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Turning a domino around does not change its equivalence class. Sorting its two ends gives a canonical key. When another domino with that key arrives, it creates one new pair with every earlier occurrence.
Approach
Maintain a frequency map keyed by (smallerEnd, largerEnd). For each domino, add the key's current frequency to the answer before increasing that frequency. This counts each unordered index pair exactly when its later domino is processed, including pairs of double-valued dominoes such as [2, 2]. Return the accumulated count.
class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
n = len(dominoes)
res = 0
seen = defaultdict(int)
for i in range(n):
curr = (min(dominoes[i]), max(dominoes[i]))
res += seen[curr]
seen[curr] += 1
return resComplexity analysis
For n dominoes and u normalized pairs, the single hash-map pass takes O(n) expected time and O(u) auxiliary space.
