Problem
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]
.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= dominoes.length <= 4 * 10^4
dominoes[i].length == 2
1 <= dominoes[i][j] <= 9
Solution
Method 1 - Using Frequency Map
The problem asks us to count the number of pairs of equivalent dominoes. A domino [a, b]
is equivalent to [c, d]
if (a == c and b == d)
or (a == d and b == c)
.
To simplify the comparison, we can treat each domino as a sorted tuple (min(a, b), max(a, b))
. This ensures that equivalent dominoes will have the same representation regardless of their order.
Here are the steps:
- Transform Dominoes: Convert each domino to its canonical form
(min(a, b), max(a, b))
. - Count Frequencies: Use a dictionary or hash map to store the frequency of each canonical form.
- Calculate Pairs: For each canonical form with a count
x
, the number of pairs is calculated using the formulax * (x - 1) // 2
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
.We traverse the list of dominoes once (O(n)
), and calculating pairs for each unique domino isO(1)
. - 🧺 Space complexity:
O(u)
. Whereu
is the number of unique domino representations stored in the hash map.