Solving Leetcode Interviews in Seconds with AI: Number of Equivalent Domino Pairs
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1128" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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 * 104 dominoes[i].length == 2 1 <= dominoes[i][j] <= 9
Explanation
Here's an efficient solution to the domino equivalence problem:
Canonical Representation: Convert each domino
[a, b]into a canonical representation by sorting its elements, i.e.,min(a, b), max(a, b). This ensures that equivalent dominoes have the same representation.Counting: Use a dictionary (or hash map) to count the occurrences of each canonical domino representation.
Pair Calculation: For each unique domino, the number of equivalent pairs can be calculated using the formula n * (n - 1) / 2, where n is the count of that domino. Sum these values for all unique dominoes to get the final result.
Complexity: O(N), where N is the number of dominoes. Space complexity is O(N) in the worst case (all dominoes are unique).
Code
def num_equiv_dominoes(dominoes):
"""
Counts the number of equivalent domino pairs.
Args:
dominoes: A list of dominoes represented as lists of two integers.
Returns:
The number of equivalent domino pairs.
"""
counts = {}
for domino in dominoes:
# Create canonical representation by sorting the domino
canonical = tuple(sorted(domino))
# Increment the count for this canonical domino
counts[canonical] = counts.get(canonical, 0) + 1
# Calculate the total number of pairs
total_pairs = 0
for count in counts.values():
total_pairs += count * (count - 1) // 2
return total_pairs