↓Skip to main content
  1. LeetCode/

LeetCode 1128: Number of Equivalent Domino Pairs

·2 mins· ·
LeetCode Easy Array Hash-Table Counting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-10-18

  • Submissions: Runtime Error ×2 → Wrong Answer ×3 → Accepted

Approach
#

[a, b] and [b, a] are the same, so normalize to (min, max) as the key (Hash Table Template 5). A key with c dominoes forms c(c - 1) / 2 pairs. Or accumulate while scanning: each domino pairs with every earlier one of the same key, so add the current count.

My Attempts
#

  • The first two used sorted(dominoe), a list, as the key, and lists are unhashable (TypeError); they also returned max(d.values()).
  • With tuple(dominoe) there was no sorting, so [1, 3] and [3, 1] counted as different, and the pair count was (i * i - 1) // 2. tuple(sorted(...)) with v * (v - 1) // 2 passed.

Solution
#

class Solution:
    def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
        cnt = Counter()
        pairs = 0
        for a, b in dominoes:
            key = (min(a, b), max(a, b))
            pairs += cnt[key]
            cnt[key] += 1
        return pairs

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Lists cannot be dict keys; use tuples.
  • Normalize the order: [1, 3] and [3, 1] are the same.
  • The pair count is c(c - 1) / 2.

Interview Explanation
#

I normalize each domino to a tuple with the smaller value first, add the number of earlier dominoes of the same kind to the answer, then increment its count. Time O(n).

Related

LeetCode 914: X of a Kind in a Deck of Cards
·2 mins
LeetCode Easy Array Hash-Table Math Counting
LeetCode 914 note: every card count must be divisible by one X >= 2, i.e. the GCD of all counts is at least 2
LeetCode 819: Most Common Word
·2 mins
LeetCode Easy Array Hash-Table String Counting
LeetCode 819 note: replace punctuation with spaces, lowercase, split, count, and pick the most frequent word not banned
LeetCode 1160: Find Words That Can Be Formed by Characters
·1 min
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 note: a word is formable when none of its character counts exceeds chars’; sum the lengths of such words
LeetCode 1122: Relative Sort Array
·1 min
LeetCode Easy Array Hash-Table Sorting Counting-Sort
LeetCode 1122 note: count first, emit values in arr2’s order, then append the remaining values in ascending order
LeetCode 1189: Maximum Number of Balloons
·2 mins
LeetCode Easy Hash-Table String Counting
LeetCode 1189 note: each letter supports count // needed balloons, with l and o needed twice; take the minimum
LeetCode 1002: Find Common Characters
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 1002 note: count each word and intersect all Counters (minimum count per character), then expand