Number of Equivalent Domino Pairs — LeetCode 1128 Python Solution
- Problem
- #1128
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The 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].
Example
- Input
- dominoes = [[1,2],[2,1],[3,4],[5,6]]
- Output
- 1
Python solution
class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
cnt = Counter()
ans = 0
for a, b in dominoes:
x = a * 10 + b if a < b else b * 10 + a
ans += cnt[x]
cnt[x] += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(C) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1128. Number of Equivalent Domino Pairs is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1128. Number of Equivalent Domino Pairs?
- LeetCode 1128. Number of Equivalent Domino Pairs is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1128. Number of Equivalent Domino Pairs?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1128. Number of Equivalent Domino Pairs?
- The Python solution on this page uses O(C) auxiliary space.
- What topics does LeetCode 1128. Number of Equivalent Domino Pairs cover?
- LeetCode 1128. Number of Equivalent Domino Pairs is tagged Array, Hash Table and Counting on LeetCode.