#1726

Tuple with Same Product

Medium
ArrayHash TableCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

Instead of checking all pairs, we can use a hash map to count the occurrences of each product formed by pairs of numbers. This allows us to efficiently calculate the number of valid tuples without redundant checks.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a hash map to count the frequency of each product formed by pairs of numbers.
  2. 2Step 2: Iterate through each unique pair of numbers, calculate their product, and update the hash map.
  3. 3Step 3: For each product that has a frequency greater than 1, calculate the number of valid tuples using the formula: count * (count - 1) * 2.
solution.py15 lines
1# Full working Python code
2from collections import defaultdict
3
4def tupleSameProduct(nums):
5    product_count = defaultdict(int)
6    n = len(nums)
7    for i in range(n):
8        for j in range(i + 1, n):
9            product = nums[i] * nums[j]
10            product_count[product] += 1
11    count = 0
12    for value in product_count.values():
13        if value > 1:
14            count += value * (value - 1) * 2
15    return count

Complexity note: The time complexity remains O(n²) due to the nested loops, but we use a hash map to store product counts, which increases space complexity to O(n).

  • 1Distinct integers mean that each product will be unique to a pair of numbers.
  • 2The number of valid tuples can be derived from the frequency of each product.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.