Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Number of Equivalent Domino Pairs in Python
When working with domino pairs, we need to find equivalent dominos where one can be flipped to match another. Two dominos D[i] = [a, b] and D[j] = [c, d] are equivalent if a = c and b = d, or a = d and b = c (since dominos can be reversed). We need to count all pairs (i, j) where 0 ? i
For example, with dominos [[1, 2], [2, 1], [3, 4], [6, 5]], we have one equivalent pair: [1, 2] and [2, 1].
Algorithm
To solve this problem, we follow these steps:
- Initialize answer = 0
- For each domino pair in the list:
- Sort the pair to normalize it (so [1, 2] and [2, 1] become [1, 2])
- Store the frequency of each normalized domino in a dictionary
- For each frequency count in the dictionary:
- Add (count * (count - 1)) / 2 to answer (combination formula for pairs)
- Return the total answer
Implementation
Here's the complete solution ?
class Solution:
def numEquivDominoPairs(self, dominoes):
domino_count = {}
answer = 0
# Normalize each domino by sorting and count frequencies
for domino in dominoes:
domino.sort()
normalized = tuple(domino)
if normalized not in domino_count:
domino_count[normalized] = 1
else:
domino_count[normalized] += 1
# Calculate pairs using combination formula
for count in domino_count.values():
answer += (count * (count - 1)) // 2
return answer
# Test the solution
solution = Solution()
result = solution.numEquivDominoPairs([[1,2],[2,1],[3,4],[5,6],[4,3]])
print("Number of equivalent domino pairs:", result)
Number of equivalent domino pairs: 2
How It Works
The algorithm works by normalizing dominos through sorting. This ensures that [1, 2] and [2, 1] are treated as the same domino [1, 2]. We then count how many times each normalized domino appears.
For each group of equivalent dominos with count n, the number of pairs we can form is C(n, 2) = n × (n - 1) / 2. This is because we're choosing 2 dominos from n identical ones.
Example Walkthrough
With input [[1,2],[2,1],[3,4],[5,6],[4,3]]:
- Normalize dominos: [1,2], [1,2], [3,4], [5,6], [3,4]
- Count frequencies: {(1,2): 2, (3,4): 2, (5,6): 1}
- Calculate pairs:
- (1,2) appears 2 times: 2×1/2 = 1 pair
- (3,4) appears 2 times: 2×1/2 = 1 pair
- (5,6) appears 1 time: 1×0/2 = 0 pairs
- Total: 1 + 1 + 0 = 2 pairs
Conclusion
This solution efficiently counts equivalent domino pairs by normalizing dominos through sorting and using the combination formula. The time complexity is O(n) where n is the number of dominos, making it an optimal approach for this problem.
