- 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 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 Articles
- Python program to count pairs for consecutive elements
- Program to count indices pairs for which elements sum is power of 2 in Python
- Program to find smallest index for which array element is also same as index in Python
- Count of index pairs with equal elements in an array in C++
- Program to count nice pairs in an array in Python
- Program to find array by swapping consecutive index pairs in Python
- Program to find number of quadruples for which product of first and last pairs are same in Python
- Python – Elements with same index
- Count index pairs which satisfy the given condition in C++
- Python program to count Bidirectional Tuple Pairs
- 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++
- C++ program for the Array Index with same count of even or odd numbers on both sides?
- Python – Check if elements index are equal for list elements
- Maximum count of pairs which generate the same sum in C++

Advertisements