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].
Example 1:
Input: dominoes = [[1,2],[2,1],[3,4],[5,6]] Output: 1
Example 2:
Input: dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]] Output: 3
Constraints:
1 <= dominoes.length <= 4 * 104dominoes[i].length == 21 <= dominoes[i][j] <= 9This approach involves using a hash map (or dictionary) to count all the equivalent domino pairs efficiently. For each domino, we convert it to a canonical form where the smaller number comes first. We then use this form as a key in our map to count the occurrences of each pair. For each domino processed, increment the counter by the number of times this key has been seen before.
The function numEquivDominoPairs takes a list dominoes and uses a dictionary count to store the frequency of each canonical domino form. The canonical form is a tuple with elements sorted to handle both orientations of dominoes. As we process each domino, we increment our pairs count by how many times the canonical form has been seen before in count. Finally, we return the total number of pairs found.
Java
Time Complexity: O(n), where n is the number of dominoes.
Space Complexity: O(n) to store the frequency of each domino pair.
This approach involves treating domino pairs as numbers to use their hash for direct indexing in an array (similar to a fixed-size hash map). By assigning a unique number to each domino combination using arithmetic, we can efficiently tally counts of equivalent pairs in a fixed-size array.
In this approach, we create an array count with size 100 (based on the possible values of [1-9, 1-9]). For each domino, we compute an integer key to represent it uniquely in both orientations. The key is derived by ensuring the smaller of the two numbers comes first, effectively treating the domino as a two-digit number. We then use this key to incrementally calculate pairs using direct array indexing.
Java
Time Complexity: O(n), where n is the number of dominoes.
Space Complexity: O(1), as the size of the array is fixed and unrelated to input size.
| Approach | Complexity |
|---|---|
| Using Hash Map for Count Tracking | Time Complexity: O(n), where n is the number of dominoes. |
| Counting Using Array Indexing | Time Complexity: O(n), where n is the number of dominoes. |
Number of Good Pairs - Leetcode 1512 - Python • NeetCodeIO • 18,103 views views
Watch 9 more video solutions →Practice Number of Equivalent Domino Pairs with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor