Python 1726.py
class Solution:
def tupleSameProduct(self, nums: List[int]) -> int:
products = defaultdict(int)
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
products[nums[i] * nums[j]] += 1
result = 0
for p in products.values():
# triangle number without self-matching
# => compute triangle(p - 1)
triangle = p * (p - 1) // 2
# and there are 8 combinations:
# ab = cd, ab = dc, ba = cd, ba = dc,
# cd = ab, dc = ab, cd = ba, dc = ba
result += 8 * triangle
return result
Difficulty
and has an acceptance rate of about 70% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Counting
- Hash Table
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The tupleSameProduct method receives a list of integers and returns the total number of ordered quadruples (a, b, c, d) with distinct indices such that the product of the first pair equals the product of the second pair. The implementation relies on counting how many unordered index pairs share the same product and then applying combinatorial reasoning to derive the number of ordered quadruples from those counts.
Key Steps
Building a frequency map of pairwise products
The algorithm iterates over every unordered pair of positions (i, j) with i < j. For each pair it computes the product of the two numbers and increments a counter associated with that product in a dictionary-like container.
products = defaultdict(int)
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
products[nums[i] * nums[j]] += 1
The nested loops guarantee that each combination of two distinct indices is examined exactly once, and the defaultdict automatically creates a zero entry for a previously unseen product, keeping the code concise.
Translating pair frequencies into ordered quadruple counts
After the first pass, each entry in products holds the number p of unordered index pairs that yield the same product. For a given p, the number of ways to pick two different pairs is the triangular number p · (p - 1) / 2. The code computes this value and multiplies it by 8 to account for all possible orderings of the two pairs and the two elements inside each pair.
result = 0
for p in products.values():
triangle = p * (p - 1) // 2
result += 8 * triangle
Finally, the accumulated result is returned.
Edge Cases Handled
When the input list contains fewer than two elements, the outer loop never enters the inner loop, leaving the products map empty. Consequently the second loop iterates over an empty collection, and the method returns 0, correctly indicating that no valid quadruples exist.
If many elements share the same value, the product calculation may produce identical results for many different index pairs. The frequency map aggregates all such occurrences, and the triangular-number formula automatically excludes the case where the two selected pairs are the same pair, thereby preventing self-matching.
The integer division operator (//) ensures that the triangular number is computed as an integer even when the intermediate product is odd, preserving exactness for all possible counts.
Performance Optimizations
The use of a hash-based dictionary to store product frequencies provides constant-time updates for each pair, avoiding the need for secondary data structures or repeated scans. By counting unordered pairs first and then applying a closed-form combinatorial expression, the algorithm eliminates the exponential blow-up that would arise from enumerating every possible quadruple explicitly.
All arithmetic operations are performed with plain integers, and the inner product calculation reuses the already-read values from the list without any additional copying. The two-phase approach-pair counting followed by a single pass over the distinct products-keeps the overall work proportional to the number of unordered pairs, which is the minimal amount of work required to capture all necessary relationships.
ELI5 - Simplified Explanation
Imagine having a big box filled with numbered blocks. The goal is to find pairs of blocks that create the same matching total when multiplied together.
First, the code goes through every possible pair of blocks in the box. It picks two blocks, multiplies their numbers, and keeps a tally of how many times each specific total appears. If the number twenty appears as a result from different pairs, those pairs are grouped together in a list.
Once all the pairs are checked and grouped by their totals, the code looks at those groups. When there are several pairs that result in the same total, it means those pairs can be swapped around in different ways to make matching sets of four. The code calculates how many ways these pairs can be arranged into the specific group of four that the puzzle asks for. It does this by looking at how many pairs share the same total and using a little bit of math to multiply those possibilities, ensuring every version is counted. After looking through all the totals, the final number of ways is collected.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | ||||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fsq | C++ | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| Shamik07 | Dart | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fsq | C++ | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| Shamik07 | Dart | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 1400: Construct K Palindrome Strings
- problem 1442: Count Triplets That Can Form Two Arrays of Equal XOR
- problem 1519: Number of Nodes in the Sub-Tree With the Same Label
- problem 1577: Number of Ways Where Square of Number Is Equal to Product of Two Numbers
- problem 1593: Split a String Into the Max Number of Unique Substrings
- problem 1604: Alert Using Same Key-Card Three or More Times in a One Hour Period
- problem 1638: Count Substrings That Differ by One Character
- problem 1695: Maximum Erasure Value
- problem 1368: Minimum Cost to Make at Least One Valid Path in a Grid
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality