- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

- Related Questions & Answers
- Count number of pairs (i, j) such that arr[i] * arr[j] > arr[i] + arr[j] in C++
- Count of unique pairs (arr[i], arr[j]) such that i < j in C++
- Count of pairs of (i, j) such that ((n % i) % j) % n is maximized in C++
- Count pairs (i,j) such that (i+j) is divisible by both A and B in C++
- Count unordered pairs (i,j) such that product of a[i] and a[j] is power of two in C++
- Python - Make pair from two list such that elements are not same in pairs
- Count the number of pairs (i, j) such that either arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i] in C++
- Count pairs in an array such that LCM(arr[i], arr[j]) > min(arr[i],arr[j]) in C++
- Find pairs with given sum such that elements of pair are in different rows in Python
- Program to find number of quadruples for which product of first and last pairs are same in Python
- Program to find a pair (i, j) where nums[i] + nums[j] + (i -j) is maximized in Python?
- Maximum difference of indices (i, j) such that A[i][j] = 0 in the given matrix in C++
- Count pairs in an array that hold i*arr[i] > j*arr[j] in C++
- Rearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < i in C++
- Program to find number of subsequences with i, j and k number of x, y, z letters in Python

Advertisements