Tuple with Same Product — LeetCode 1726 Python Solution

MediumArrayHash TableCounting
Problem
#1726
Pattern
Hash Map
Reading time
2 min

The problem

Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a, b, c, and d are elements of nums, and a != b != c != d.

Example

Input
nums = [2,3,4,6]
Output
8
Explanation
There are 8 valid tuples:

Python solution

Python
class Solution:
    def tupleSameProduct(self, nums: List[int]) -> int:
        cnt = defaultdict(int)
        for i in range(1, len(nums)):
            for j in range(i):
                x = nums[i] * nums[j]
                cnt[x] += 1
        return sum(v * (v - 1) // 2 for v in cnt.values()) << 3

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n^2) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1726. Tuple with Same Product is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1726. Tuple with Same Product?
LeetCode 1726. Tuple with Same Product is rated Medium on LeetCode.
What is the time complexity of LeetCode 1726. Tuple with Same Product?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 1726. Tuple with Same Product?
The Python solution on this page uses O(n^2) auxiliary space.
What topics does LeetCode 1726. Tuple with Same Product cover?
LeetCode 1726. Tuple with Same Product is tagged Array, Hash Table and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview