Tuple with Same Product - 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.

All four elements must be different from each other, and their products must be equal.

Input & Output

Example 1 — Basic Case
$ Input: nums = [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), (4,3,2,6), (3,4,6,2), (4,3,6,2). All satisfy a*b = c*d where 2*6 = 3*4 = 12.
Example 2 — Single Element Repeated Product
$ Input: nums = [1,2,4,5,10]
Output: 16
💡 Note: Product 10 appears 3 times: 1*10, 2*5, so we get 3*(3-1) = 6 tuples. Product 20 appears 2 times: 2*10, 4*5, so we get 2*(2-1) = 2 tuples. Total is 6+2 = 8 tuples, but accounting for all permutations gives 16.
Example 3 — No Valid Tuples
$ Input: nums = [2,3,5,7]
Output: 0
💡 Note: All numbers are prime, so no two different pairs can have the same product. Products are: 2*3=6, 2*5=10, 2*7=14, 3*5=15, 3*7=21, 5*7=35. All unique, so 0 tuples.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 104
  • All elements in nums are distinct

Visualization

Tap to expand
Tuple with Same Product INPUT Array nums (distinct positives) 2 3 4 6 [0] [1] [2] [3] Find tuples (a,b,c,d) where: a * b = c * d All elements distinct Sample Products: 2*3=6, 2*4=8, 2*6=12 3*4=12, 3*6=18, 4*6=24 nums = [2, 3, 4, 6] ALGORITHM (Hash Map) 1 Calculate Products For each pair (i,j) 2 Store in Hash Map product --> count Product Map 6 --> 1 8 --> 1 12 --> 2 18 --> 1 24 --> 1 3 Count Pairs If count=n: C(n,2) pairs 4 Multiply by 8 Each pair: 8 tuples result = 8 * C(n,2) per product FINAL RESULT Matching Product: 12 2*6 = 12 and 3*4 = 12 8 Valid Tuples: 1. (2, 6, 3, 4) 2. (2, 6, 4, 3) 3. (6, 2, 3, 4) 4. (6, 2, 4, 3) 5. (3, 4, 2, 6) 6. (3, 4, 6, 2) 7. (4, 3, 2, 6) 8. (4, 3, 6, 2) 1 pair with same product = 1 * 8 = 8 tuples Output: 8 Key Insight: Use a hash map to count pairs with same product. For each product appearing n times, there are C(n,2) = n*(n-1)/2 pair combinations. Each pair of pairs forms 8 distinct tuples (2 choices for first pair order * 2 for second * 2 for which pair comes first). TutorialsPoint - Tuple with Same Product | Hash Map Approach
Asked in
Google 15 Facebook 12 Amazon 8
31.2K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen