- 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

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

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))

[5, 4, 5, 4, 4]

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++
- Python – Elements with same index
- Program to count nice pairs in an array in Python
- Program to find array by swapping consecutive index pairs in Python
- Python – Check if elements index are equal for list elements
- Program to find number of pairs (i, j) such that ith and jth elements are same in Python
- Count pairs with average present in the same array in C++
- 8085 program to count number of elements which are less than 0A
- Python program to count Bidirectional Tuple Pairs

Advertisements