- 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 count index pairs for which array elements are same in Python

Suppose we have a list of numbers called nums. We have to find the number of pairs i < j such that nums[i] and nums[j] are same.

So, if the input is like nums = [5, 4, 5, 4, 4], then the output will be 4, as We have index pairs like (0, 2), (1, 3), (1, 4) and (3, 4).

To solve this, we will follow these steps −

c := a list containing frequencies of each elements present in nums

count := 0

for each n in list of all values of c, do

count := count + floor of (n *(n - 1)) / 2

return count

## Example

Let us see the following implementation to get better understanding

from collections import Counter def solve(nums): c = Counter(nums) count = 0 for n in c.values(): count += n * (n - 1) // 2 return count nums = [5, 4, 5, 4, 4] print(solve(nums))

## Input

[5, 4, 5, 4, 4]

## Output

4

- Related Questions & Answers
- Python program to count pairs for consecutive elements
- Program to find smallest index for which array element is also same as index in Python
- Program to count indices pairs for which elements sum is power of 2 in Python
- Program to find number of quadruples for which product of first and last pairs are same in Python
- Count of index pairs with equal elements in an array in C++
- Count index pairs which satisfy the given condition in C++
- Maximum count of pairs which generate the same sum in C++
- Program to count nice pairs in an array in Python
- Python – Elements with same index
- Program to find array by swapping consecutive index pairs in Python
- Count pairs with average present in the same array in C++
- Python program to count Bidirectional Tuple Pairs
- C++ program to find permutation for which sum of adjacent elements sort is same as given array
- Program to find number of pairs (i, j) such that ith and jth elements are same in Python
- 8085 program to count number of elements which are less than 0A

Advertisements