Program to find number of pairs (i, j) such that ith and jth elements are same in Python



Suppose we have an array nums. We have to find number of pairs (i,j) are there such that nums[i] = nums[j] but i is not same as j.

So, if the input is like nums = [1,3,1,3,5], then the output will be 4, because the pairs are (0,2), (2,0), (1,3) and (3,1)

To solve this, we will follow these steps −

  • d := a new map
  • for each c in nums, do
    • d[c] := (d[c] + 1) when c is present in d otherwise 1
  • res := 0
  • for each c is in the list of elements (x for all x in d where d[x] > 1), do
    • res := res +(d[c] *(d[c]-1))
  • return res

Example

Let us see the following implementation to get better understanding −

def solve(nums):
   d = {}
   for c in nums:
      d[c] = d[c] + 1 if c in d.keys() else 1

   res = 0
   for c in (x for x in d if d[x] > 1):
      res += (d[c] * (d[c]-1))

   return res

nums = [1,3,1,3,5]
print(solve(nums))

Input

[1,3,1,3,5]

Output

4

Advertisements