Leetcode 1128. Number of Equivalent Domino Pairs
Given a list of dominoes, dominoes[i] = [a, b]
is equivalent to dominoes[j] = [c, d]
if and only if:
i.e., one is simply a rotation of the other.
Return the number of pairs (i, j) for which dominoes[i]
is equivalent to dominoes[j]
(i < j).
Normalize Each Domino: For each domino [a, b]
, treat it as [min(a, b), max(a, b)]
to create a normalized form.
Count Dominoes: Use a hashmap to count occurrences of each normalized domino.
Calculate Pairs: The number of ways to pick 2 out of n same items is given by the combination formula C(n, 2)
which is n * (n - 1) / 2
. Use this formula to calculate the number of equivalent pairs for each count in the hashmap.
With these steps, we can ensure an efficient solution.
import java.util.HashMap;
import java.util.Map;
public class DominosEquivalentPairs {
public int numEquivDominoPairs(int[][] dominoes) {
Map<Integer, Integer> countMap = new HashMap<>();
int numPairs = 0;
for (int[] domino : dominoes) {
int key = domino[0] < domino[1] ? domino[0] * 10 + domino[1] : domino[1] * 10 + domino[0];
countMap.put(key, countMap.getOrDefault(key, 0) + 1);
}
for (int count : countMap.values()) {
if (count > 1) {
numPairs += count * (count - 1) / 2;
}
}
return numPairs;
}
public static void main(String[] args) {
DominosEquivalentPairs sol = new DominosEquivalentPairs();
int[][] dominoes = \ use example from above
System.out.println(sol.numEquivDominoPairs(dominoes)); // Output: 1
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?