Program to find number of pairs (i, j) such that ith and jth elements are same in Python

Given an array nums, we need to find the number of pairs (i, j) where nums[i] = nums[j] but i ? j. This means we're looking for indices that point to the same value, excluding pairs where an element is paired with itself.

For example, if the input is nums = [1, 3, 1, 3, 5], the output will be 4, because the pairs are (0, 2), (2, 0), (1, 3), and (3, 1).

Algorithm

To solve this, we follow these steps:

  • Create a frequency map to count occurrences of each element
  • For each element that appears more than once, calculate pairs using the formula: count × (count - 1)
  • Sum all the pairs to get the final result

Example

Let us see the implementation to get better understanding ?

def solve(nums):
    # Create frequency map
    frequency = {}
    for element in nums:
        frequency[element] = frequency.get(element, 0) + 1
    
    # Count pairs for elements appearing more than once
    pairs = 0
    for element, count in frequency.items():
        if count > 1:
            pairs += count * (count - 1)
    
    return pairs

# Test with example
nums = [1, 3, 1, 3, 5]
result = solve(nums)
print(f"Input: {nums}")
print(f"Number of pairs: {result}")
Input: [1, 3, 1, 3, 5]
Number of pairs: 4

How It Works

The algorithm works by counting frequency of each element. For an element appearing n times, we can form n × (n - 1) ordered pairs, since each occurrence can be paired with every other occurrence in both directions.

In our example:

  • Element 1 appears 2 times: 2 × (2 - 1) = 2 pairs
  • Element 3 appears 2 times: 2 × (2 - 1) = 2 pairs
  • Element 5 appears 1 time: no pairs possible
  • Total pairs: 2 + 2 = 4

Alternative Approach Using Collections

We can also use Python's Counter from collections module for cleaner code ?

from collections import Counter

def solve_with_counter(nums):
    frequency = Counter(nums)
    return sum(count * (count - 1) for count in frequency.values() if count > 1)

# Test with example
nums = [1, 3, 1, 3, 5]
result = solve_with_counter(nums)
print(f"Result using Counter: {result}")
Result using Counter: 4

Conclusion

The solution uses frequency counting and the mathematical formula n × (n - 1) to efficiently count pairs. The time complexity is O(n) and space complexity is O(k) where k is the number of unique elements.

Updated on: 2026-03-26T18:21:40+05:30

364 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements