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
Domino Normalization Process[2,1][1,2][3,4][1,2][1,2][3,4]Hash Map[1,2]: 2 occurrences1 Pair Found!Normalization: Always put smaller value firstThis ensures [1,2] and [2,1] are treated as identical
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!
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 4
28.5K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen