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
.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 104
- All elements in
nums
are distinct.
Solution
Video explanation
Here is the video explaining this method in detail. Please check it out:
Method 1 - Naive
The naive solution for this problem would involve iterating over all possible quadruplets (a, b, c, d) and checking if they satisfy the condition a * b = c * d
. This can be achieved using four nested loops.
Approach:
- Iterate Over All Quadruplets:
- Use four nested loops to iterate over every combination of
a
,b
,c
, andd
in the arraynums
.
- Use four nested loops to iterate over every combination of
- Check the Product Condition:
- For each quadruplet
(a, b, c, d)
, check ifa * b
is equal toc * d
.
- For each quadruplet
- Ensure Distinct Elements:
- Ensure that all four elements
a
,b
,c
, andd
are distinct.
- Ensure that all four elements
- Count Valid Quadruplets:
- Count the number of valid quadruplets that satisfy the conditions.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^4)
because there are four nested loops each iterating overn
elements. - 🧺 Space complexity:
O(1)
because we are not using any extra space proportional to the input size.
Method 2 - Using Frequency Map
Given distinct positive integers in the array nums
, we need to find tuples (a, b, c, d) such that a * b = c * d
and a != b != c != d
.
We can utilize a HashMap (or dictionary in Python) to store the product of pairs and the list of indices that create that product.
Here is the approach:
- Iterate over all pairs of elements in the array.
- Calculate the product of each pair and store it in a HashMap along with the pairs’ indices.
- Check if the product has already been seen. If yes, count how many valid tuples can be formed.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
wheren
is the length of the array because we iterate through all pairs. - 🧺 Space complexity:
O(n^2)
in the worst case if all pairs have unique products, but generally lower since it’s based on the number of unique products.