Number of Equivalent Domino Pairs - 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].

Input & Output

Example 1 — Basic Case
$ Input: dominoes = [[1,2],[2,1],[3,4],[5,6]]
Output: 1
💡 Note: [1,2] and [2,1] are equivalent (one can be rotated to match the other), so there's 1 equivalent pair
Example 2 — Multiple Pairs
$ Input: dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]]
Output: 3
💡 Note: Three [1,2] dominoes form 3 pairs: (0,1), (0,3), (1,3). Other dominoes don't have matches.
Example 3 — No Equivalent Pairs
$ Input: dominoes = [[1,1],[2,2],[1,3]]
Output: 0
💡 Note: No two dominoes are equivalent, so there are 0 pairs

Constraints

  • 1 ≤ dominoes.length ≤ 4 × 104
  • dominoes[i].length == 2
  • 1 ≤ dominoes[i][j] ≤ 9

Visualization

Tap to expand
Number of Equivalent Domino Pairs INPUT 1 2 i=0 2 1 i=1 EQUIV 3 4 i=2 5 6 i=3 dominoes = [ [1,2],[2,1],[3,4],[5,6] ] ALGORITHM STEPS 1 Normalize each domino key = min*10 + max 2 Store in HashMap Count occurrences Key Count 12 (1,2) 2 34 (3,4) 1 56 (5,6) 1 3 Count pairs pairs = n*(n-1)/2 4 Sum all pairs For count=2: 2*1/2=1 FINAL RESULT Equivalent Pair Found: 1 2 = 2 1 Rotated Calculation: Key 12 appears 2 times Pairs = 2*(2-1)/2 = 1 OUTPUT 1 OK - 1 equivalent pair Key Insight: Normalize each domino by creating a unique key: key = min(a,b) * 10 + max(a,b). This ensures [1,2] and [2,1] both map to key 12. Use a HashMap to count occurrences, then compute pairs using combination formula: n*(n-1)/2. Time: O(n), Space: O(n). TutorialsPoint - Number of Equivalent Domino Pairs | Hash Approach
Asked in
Google 15 Amazon 12 Microsoft 8
25.0K 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