Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created February 6, 2025 21:51
Show Gist options
  • Save Ifihan/a6dc55002459dc45c3b524166cfc71b9 to your computer and use it in GitHub Desktop.
Save Ifihan/a6dc55002459dc45c3b524166cfc71b9 to your computer and use it in GitHub Desktop.
Tuple with Same Product

Question

Approach

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.

Implementation

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

Complexities

  • Time: O(n^2)
  • Space: O(n^2)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment