Problem Description
Given a list of domino pairs, where each domino is represented as [a, b], determine the number of pairs (i, j) such that dominoes[i] is equivalent to dominoes[j]. Two dominoes are equivalent if one can be rotated to become equal to the other (i.e., either a == c and b == d, or a == d and b == c).
Key Insights
- A domino [a, b] is equivalent to [b, a], so normalization by sorting each pair makes comparison easier.
- Use a hash table (or dictionary) to count the occurrence of each normalized domino representation.
- For each domino type with frequency f, the number of equivalent pairs is f * (f - 1) / 2.
- The solution runs with a single pass over the list for counting and a second pass over the hash table for pair calculation.
Space and Time Complexity
Time Complexity: O(n), where n is the number of dominoes. Space Complexity: O(n) in the worst case for the hash table storage.
Solution
The approach is to convert each domino to its normalized form by sorting the pair (ensuring the smaller number comes first). Then, use a hash table to count how many times each normalized domino appears. Finally, calculate the number of pairs using the combination formula n * (n - 1) / 2 for each unique domino, and sum all these pair counts. This method avoids any unnecessary comparisons and efficiently solves the problem.