LeetCode 1726: Tuple with Same Product
Problem Description
Explanation:
To solve this problem, we can first generate all possible pairs of elements from the given array nums
, calculate the product of each pair, and store the count of that product in a hashmap. Then, for each product encountered, we can calculate the total number of valid tuples that can be formed using the pairs that resulted in that product. The total number of tuples for a particular product is given by nC2 * mC2, where n is the count of one pair and m is the count of the other pair. We need to consider all possible permutations of the pairs as order matters in tuples.
- Generate all pairs and calculate products.
- Store product counts in a hashmap.
- For each product, calculate the total number of tuples that can be formed.
Time complexity: O(n^2) where n is the length of the input array nums
.
Space complexity: O(n^2) to store the product counts in a hashmap.
:
Solutions
class Solution {
public int tupleSameProduct(int[] nums) {
Map<Integer, Integer> productCount = new HashMap<>();
int count = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
int product = nums[i] * nums[j];
productCount.put(product, productCount.getOrDefault(product, 0) + 1);
}
}
for (int value : productCount.values()) {
count += value * (value - 1) * 4;
}
return count;
}
}
Loading editor...