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). Return the number of pairs (i, j) where dominoes[i] is equivalent to dominoes[j].
LeetCode-1128: Given a list of dominoes, dominoes[i] = [a, b]
is equivalent to dominoes[j] = [c, d]
if and only if either both are same or one can be rotated to be equal to the other.
Return the number of pairs (i, j)
for which 0 <= i < j < dominoes.length
, and dominoes[i]
is equivalent to dominoes[j]
.
This problem is about finding equivalent domino pairs in a list of dominoes where two dominoes are considered equivalent if they have the same values (possibly in reversed order).
For each domino [a,b]
, we can create a standardized key by ensuring
Consider the following example: [[1,2],[2,1],[3,4],[5,6]]
Additionally, based on the constraint 1 <= dominoes[i][j] <= 9
, we can use a fixed-size array to count the occurrences of each domino. This will help us avoid using a dictionary and make the solution more efficient.
public int numEquivDominoPairs(int[][] dominoes) {
int ans = 0;
int[] freq = new int[100];
for(int[] pair : dominoes){
// normalize the dominos
// so that the smaller number is always first
// e.g. [1,2] and [2,1] both become 12
// [3,4] becomes 34
// this way we can use the same index for both the flavors
int val = pair[0] < pair[1] ?
pair[0]*10 + pair[1] :
pair[1]*10 + pair[0];
ans+= freq[val];
freq[val]++;
}
return ans;
}
Be notified of new posts. Subscribe to the RSS feed.