- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# 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 Articles
- 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++
- Python - Make pair from two list such that elements are not same in pairs
- 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++
- 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++
- Find pairs with given sum such that elements of pair are in different rows in Python
- Count pairs in an array such that LCM(arr[i], arr[j]) > min(arr[i],arr[j]) in C++
- Program to find number of quadruples for which product of first and last pairs are same in Python
- Program to count index pairs for which array elements are same in Python
- Program to find a pair (i, j) where nums[i] + nums[j] + (i -j) is maximized in Python?
- Program to find number of subsequences with i, j and k number of x, y, z letters in Python
- Program to find number of operations needed to make pairs from first and last side are with same sum in Python
- Count pairs in an array that hold i*arr[i] > j*arr[j] in C++

Advertisements