Tuple with Same Product - Problem
Find Tuples with Equal Products
Given an array of distinct positive integers, your task is to count how many unique 4-tuples (a, b, c, d) exist such that:
•
• All four numbers are different from each other
• All four numbers come from the input array
For example, if
Goal: Return the total count of such valid tuples.
Note: Different orderings of the same four numbers count as separate tuples. So if
Given an array of distinct positive integers, your task is to count how many unique 4-tuples (a, b, c, d) exist such that:
•
a × b = c × d (products are equal)• All four numbers are different from each other
• All four numbers come from the input array
For example, if
nums = [2, 3, 4, 6], then (2, 6, 3, 4) is a valid tuple because 2 × 6 = 3 × 4 = 12.Goal: Return the total count of such valid tuples.
Note: Different orderings of the same four numbers count as separate tuples. So if
(a, b, c, d) is valid, then (b, a, c, d), (a, b, d, c), etc. are also counted separately. Input & Output
example_1.py — Python
$
Input:
[2, 3, 4, 6]
›
Output:
8
💡 Note:
We have 8 valid tuples: (2,6,3,4), (2,6,4,3), (6,2,3,4), (6,2,4,3), (3,4,2,6), (3,4,6,2), (4,3,2,6), (4,3,6,2). All satisfy the condition 2×6 = 3×4 = 12.
example_2.py — Python
$
Input:
[1, 2, 4, 5, 10]
›
Output:
16
💡 Note:
Two groups: (1,10,2,5) since 1×10 = 2×5 = 10, and (2,10,4,5) since 2×10 = 4×5 = 20. Each group contributes 8 tuples, total = 16.
example_3.py — Python
$
Input:
[2, 3, 5, 7]
›
Output:
0
💡 Note:
All numbers are prime, so no two pairs can have the same product. No valid tuples exist.
Visualization
Tap to expand
Understanding the Visualization
1
Register couples
As each couple registers, calculate their chemistry score (product)
2
Find matches
If another couple already has this score, they can compete!
3
Count competitions
Each match allows 8 different dance-off arrangements
4
Running total
Keep adding to our total count as we process each couple
Key Takeaway
🎯 Key Insight: Instead of checking all possible combinations later, we count matches immediately as we discover them, leading to an elegant O(n²) solution that's both time and space optimal!
Time & Space Complexity
Time Complexity
O(n²)
Single pass through all O(n²) pairs, hash operations are O(1) average case
⚠ Quadratic Growth
Space Complexity
O(n²)
Hash map stores at most O(n²) unique products
⚠ Quadratic Space
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 104
- All elements of nums are distinct
- Important: Products can be as large as 108
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code