Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created May 4, 2025 22:37
Show Gist options
  • Save Ifihan/ff3a8a9e3652d82582c3c40d1b6fd52d to your computer and use it in GitHub Desktop.
Save Ifihan/ff3a8a9e3652d82582c3c40d1b6fd52d to your computer and use it in GitHub Desktop.
Number of Equivalent Domino Pairs

Question

Approach

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.

Implementation

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

Complexities

  • Time: O(n)
  • Space: O(n)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment