Tuple with Same Product (LeetCode 1726): Solution and Explanation

Medium
Array
Hash Table
Counting

Given distinct positive integers, count the ordered tuples (a, b, c, d) of four different elements with a * b == c * d.

Intuition

A valid tuple is really two pairs, (a, b) and (c, d), that have the same product. So the question becomes: how many pairs of pairs share a product?

Because every number is distinct, two different pairs with the same product can never share a number. If a * b == a * d, then b == d. So any two pairs from the same product bucket form a valid tuple with four different elements.

One unordered match of pairs {a, b} and {c, d} can be written in 8 orders: swap inside the first pair, swap inside the second pair, and swap which pair comes first. That is 2 x 2 x 2 = 8.

So walk over every pair once, look up how many earlier pairs had the same product, and add 8 for each of them.

Approach: Hash map of product counts

  1. Create an empty map from product to the number of pairs seen with it, and set result = 0.
  2. For every pair i < j, compute p = nums[i] * nums[j].
  3. Add 8 * count[p] to result, since the new pair matches each earlier pair with product p.
  4. Increment count[p], then return result after all pairs.

Step-by-step example

nums = [2,3,4,6]
  1. Pairs (2,3)=6, (2,4)=8 and (2,6)=12 each start a new bucket. No matches yet.
  2. Pair (3,4)=12 finds one earlier pair, (2,6), in bucket 12. result += 8, so result = 8.
  3. Pairs (3,6)=18 and (4,6)=24 start new buckets and add nothing.
  4. All 6 pairs are done. Only product 12 has two pairs, so the answer is 8.

Code: Python, Java, C++

1class Solution:
2    def tupleSameProduct(self, nums: List[int]) -> int:
3        count = {}
4        result = 0
5        for i in range(len(nums)):
6            for j in range(i + 1, len(nums)):
7                p = nums[i] * nums[j]
8                result += 8 * count.get(p, 0)
9                count[p] = count.get(p, 0) + 1
10        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

There are n(n-1)/2 pairs and each one does a constant amount of hash map work.

Space

O(n^2)

In the worst case every pair has a different product and gets its own map entry.

Other approaches

Count first, then combine (time O(n^2), space O(n^2))

Fill the map with every product's pair count, then add 8 * k * (k - 1) / 2 for each count k. Same complexity and the same answer; the running version just folds the formula into the loop.

Brute force over four indices (time O(n^4), space O(1))

Try every ordered choice of four different indices and check the products. It is O(n^4), far too slow for n = 1000.

Common mistakes

  • Counting each match once instead of 8 times. The problem counts ordered tuples, so both pairs can be flipped and swapped.
  • Worrying about shared elements. With distinct numbers, two different pairs with the same product never overlap, so no extra check is needed.
  • Adding the count after incrementing it. Read the old count first, otherwise each pair matches itself.
  • Iterating j from 0 instead of i + 1, which visits each pair twice and inflates the answer.

Frequently asked questions

Why multiply by 8?

For pairs {a, b} and {c, d}, you can order a and b 2 ways, c and d 2 ways, and choose which pair goes first 2 ways, for 8 tuples.

Can two pairs with the same product share a number?

Not when the numbers are distinct. If a * b equals a * d with a positive a, then b equals d, so the pairs would be the same pair.

Can the product overflow a 32-bit integer?

No. Each value is at most 10^4, so a product is at most 10^8, which fits easily.