Suppose we have an array nums with unique positive values, we have to find 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 all elements a, b, c and d are distinct.
So, if the input is like nums = [2,3,4,6], then the output will be 8 because we can get tuples like (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).
To solve this, we will follow these steps −
- dic := an empty map, default value is 0 if some key is not present
- ans:= 0
- for i in range 0 to size of nums - 2, do
- for j in range i+1 to size of nums, do
- dic[nums[i]*nums[j]] := dic[nums[i]*nums[j]] + 1
- for j in range i+1 to size of nums, do
- for each v in list of all values of dic, do
- if v is same as 1, then
- go for next iteration
- v:= v-1
- s:= (v/2) * (8+8*v)
- ans := ans + s
- if v is same as 1, then
- return ans as integer
Example
Let us see the following implementation to get better understanding −
from collections import defaultdict def solve(nums): dic = defaultdict(int) ans=0 for i in range(len(nums)-1): for j in range(i+1,len(nums)): dic[nums[i]*nums[j]]+=1 for v in dic.values(): if v==1: continue v=v-1 s=(v/2) * (8+8*v) ans+=s return int(ans) nums = [3,4,6,2] print(solve(nums))
Input
[3,4,6,2]
Output
0