Suppose we have a list of dominos. Each domino has two numbers. Two dominos D[i] = [a, b] and D[j] = [c, d] will be same if a = c and b = d, or a = d and b = c. So one domino can be reversed. We have to return number of pairs (i, j) for which 0 <= i < j < length of Dominos, and determine D[i] is equivalent to D[j]. So if the domino list is like [[1, 2], [2, 1], [3, 4], [6, 5]]. The output will be 1
To solve this, we will follow these steps −
- let answer = 0
- for each pair p in dominos list −
- sort pair p
- Then store the frequency of each domino into D
- for b in values in D −
- answer := answer + (b * (b - 1))/2
- return answer
Example
Let us see the following implementation to get better understanding −
class Solution(object): def numEquivDominoPairs(self, dominoes): d = {} ans = 0 for i in dominoes: i.sort() i = tuple(i) if i not in d: d[i]= 1 else: d[i]+=1 for b in d.values(): ans += ((b*(b-1))//2) return ans ob1 = Solution() print(ob1.numEquivDominoPairs([[1,2],[2,1],[3,4],[5,6], [4,3]]))
Input
[[1,2],[2,1],[3,4],[5,6],[4,3]]
Output
2