Number of Equivalent Domino Pairs - Problem
Imagine you have a collection of dominoes scattered on a table. Each domino has two numbers on it, one on each end. The fascinating thing about dominoes is that you can rotate them - so a domino with [1, 2] is essentially the same as [2, 1]!
Given a list of dominoes where dominoes[i] = [a, b], your task is to find how many equivalent pairs exist. Two dominoes are equivalent if:
- They have the same numbers in the same positions:
(a == c and b == d) - OR they have the same numbers but rotated:
(a == d and b == c)
Goal: Return the number of pairs (i, j) where 0 โค i < j < dominoes.length and dominoes[i] is equivalent to dominoes[j].
Example: If you have dominoes [[1,2], [2,1], [3,4], [5,6]], then [1,2] and [2,1] form one equivalent pair, so the answer is 1.
Input & Output
example_1.py โ Basic Case
$
Input:
dominoes = [[1,2],[2,1],[3,4],[5,6]]
โบ
Output:
1
๐ก Note:
The dominoes [1,2] and [2,1] are equivalent (one can be rotated to match the other). All other dominoes are unique, so there's only 1 equivalent pair.
example_2.py โ Multiple Pairs
$
Input:
dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]]
โบ
Output:
3
๐ก Note:
We have three [1,2] dominoes at indices 0, 1, 3. They form 3 pairs: (0,1), (0,3), and (1,3). The dominoes [1,1] and [2,2] are unique.
example_3.py โ Edge Case
$
Input:
dominoes = [[1,1],[2,2],[1,1]]
โบ
Output:
1
๐ก Note:
Only the two [1,1] dominoes at indices 0 and 2 are equivalent, forming 1 pair. Note that [1,1] rotated is still [1,1].
Constraints
- 1 โค dominoes.length โค 4 ร 104
- dominoes[i].length == 2
- 1 โค dominoes[i][j] โค 9
Visualization
Tap to expand
Understanding the Visualization
1
Normalize
Convert each domino to standard form [min, max]
2
Track
Use hash map to count each normalized domino type
3
Count Pairs
For each domino, add current count to result before incrementing
4
Result
Total pairs found across all equivalent domino groups
Key Takeaway
๐ฏ Key Insight: Normalize dominoes by sorting their values, then use a hash map to count equivalent pairs in O(n) time!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code