I approached the problem by counting the frequency of each product formed by multiplying two distinct numbers in the given array. I used a dictionary where the keys represent the product values, and the values store the count of how many times each product appears.
Once I built the frequency dictionary, I calculated the number of valid tuples. If a product appears count
times, then I can select two pairs (a, b)
and (c, d)
from these count
occurrences in count * (count - 1) / 2
ways. Since each selection results in 8
valid permutations of (a, b, c, d)
, I multiplied the computed value by 8
to get the final count.
from collections import defaultdict
class Solution:
def tupleSameProduct(self, nums: List[int]) -> int:
product_count = defaultdict(int)
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
product = nums[i] * nums[j]
product_count[product] += 1
total_tuples = 0
for count in product_count.values():
if count > 1:
total_tuples += (count * (count - 1) // 2) * 8
return total_tuples
- Time: O(n^2)
- Space: O(n^2)
