If you’ve ever played with dominoes, you know that the order of the numbers doesn’t matter—[1,2] is the same as [2,1]. That's the central idea behind this popular LeetCode problem:

💡 Given a list of dominoes, return how many pairs of dominoes are equivalent. Two dominoes [a, b] and [c, d] are equivalent if:

  • (a == c and b == d) or
  • (a == d and b == c)

Let's dive into the most optimal way to solve this!


🧠 Step-by-Step Intuition

Instead of comparing every pair (which would take O(n²) time), we can:

  1. Normalize each domino: [a, b] becomes [min(a, b), max(a, b)]
  2. Use a hash map to count how many times each normalized domino appears.
  3. Every time we see a duplicate, we count how many previous identical dominoes we've seen.
  4. Add that count to the result (because every new domino can pair with all previous identical ones).

🔍 Example

Input: [[1,2],[2,1],[3,4],[5,6]]
Normalized: [[1,2], [1,2], [3,4], [5,6]]
Only [1,2] is repeated => 1 pair

Output: 1

✅ Best & Optimal Solution – O(n) Time

Let’s now solve this in three languages: C++, JavaScript, and Python.


✅ JavaScript

/**
 * @param {number[][]} dominoes
 * @return {number}
 */
var numEquivDominoPairs = function(dominoes) {
    let map = new Array(100).fill(0);
    let count = 0;

    for (let [a, b] of dominoes) {
        let key = a < b ? a * 10 + b : b * 10 + a;
        count += map[key];
        map[key]++;
    }

    return count;
};

✅ Python

from typing import List

def numEquivDominoPairs(dominoes: List[List[int]]) -> int:
    count = [0] * 100
    res = 0

    for a, b in dominoes:
        key = a * 10 + b if a < b else b * 10 + a
        res += count[key]
        count[key] += 1

    return res

✅ C++

#include 
using namespace std;

class Solution {
public:
    int numEquivDominoPairs(vector<vector<int>>& dominoes) {
        int count[100] = {0};
        int res = 0;

        for (auto& d : dominoes) {
            int a = min(d[0], d[1]);
            int b = max(d[0], d[1]);
            int key = a * 10 + b;
            res += count[key];
            count[key]++;
        }

        return res;
    }
};

🚀 Time & Space Complexity

  • Time: O(n) – one pass through the input
  • Space: O(1) – fixed array size (only 100 possible domino pairs)

🧾 Conclusion

This problem teaches an important lesson in hashing and counting pairs efficiently, a common pattern in coding interviews.

If you're preparing for front-end or full-stack interviews, even small logical challenges like this help you think better and write cleaner code. Try re-implementing this solution with different keying strategies or using a Map or dict if you're exploring data structures!


💬 Want More?

If you found this helpful:

  • 🧠 Follow for more intuitive algorithm breakdowns
  • 💬 Comment your favorite programming language
  • 🔁 Re-share this with a dev who needs a confidence boost!