Number of Equivalent Domino Pairs Problem
Description
LeetCode Problem 1128.
Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a == c and b == d), or (a == d and b == c) - that is, one domino can be rotated to be equal to another domino.
Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j].
Example 1:
Input: dominoes = [[1,2],[2,1],[3,4],[5,6]]
Output: 1
Example 2:
Input: dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]]
Output: 3
Constraints:
1 <= dominoes.length <= 4 * 10^4dominoes[i].length == 21 <= dominoes[i][j] <= 9
Solution
Approach: Normalize and Count
Two dominoes are equivalent when they hold the same two numbers in either order. Put the smaller number first and both [1,2] and [2,1] turn into the same domino. Since the numbers are between 1 and 9, the normalized domino fits in a two-digit key, 10 * min + max, which indexes an array of 100 counters.
Walk the dominoes once. For each one, every equivalent domino seen earlier forms a new pair with it, so add the current count of its key to the answer, and only then increase the count. Doing it in that order counts each pair (i, j) with i < j exactly once and never pairs a domino with itself.
Comparing every pair directly would be O(n2), too slow for 4 · 104 dominoes. The answer itself stays below 231: even 4 · 104 identical dominoes give about 8 · 108 pairs.
Complexity: O(n) time and O(1) extra space.
class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
count = [0] * 100 # count[key] = dominoes seen so far with this key
pairs = 0
for a, b in dominoes:
key = a * 10 + b if a < b else b * 10 + a # smaller digit first: [2,1] and [1,2] share key 12
pairs += count[key] # pair with every equal domino seen before
count[key] += 1
return pairs