1128. Number of Equivalent Domino Pairs Easy
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
Approach
Input: An array dominoes
Output: Determine how many pairs of equivalent dominoes there are
This is a Hash Table + Array Counting problem.
We can sort the numbers on each domino and convert them into a string or tuple to store in a hash table.
When iterating to a new domino, check the hash table for how many equivalent dominoes have appeared before, and increment the count: count += cache[key].
Finally, return the answer count.
Implementation
class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
cache = {} # Used to count occurrences of each equivalent pair
count = 0 # Final result: number of equivalent pairs
for a, b in dominoes:
# Sort the two numbers on each domino in ascending order, ensuring [1,2] and [2,1] fall into the same category
key = (min(a, b), max(a, b))
# If this combination has appeared before, there are already count[key] dominos that can be paired with the current one
if key in cache:
count += cache[key] # This current domino can form a pair with each of the existing equivalent dominos
cache[key] += 1 # Update the occurrence count
else:
cache[key] = 1 # First appearance, initialized to 1
return count/**
* @param {number[][]} dominoes
* @return {number}
*/
var numEquivDominoPairs = function(dominoes) {
const cache = new Map();
let count = 0;
for (let arr of dominoes) {
arr = [Math.min(...arr), Math.max(...arr)];
const key = String(arr);
if (cache.has(key)) {
count += cache.get(key);
cache.set(key, cache.get(key) + 1);
} else {
cache.set(key, 1);
}
}
return count;
};Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1) space since there are at most 100 possible domino pairs (from [1,1] to [9,9])
Links
1128. Number of Equivalent Domino Pairs (English)1128. 等价多米诺骨牌对的数量 (Chinese)