Suppose we have an array nums. Here a pair (i,j) is said to be a good pair if nums[i] is same as nums[j] and i < j. We have to count the number of good pairs.
So, if the input is like nums = [5,6,7,5,5,7], then the output will be 4 as there are 4 good pairs the indices are (0, 3), (0, 4) (3, 4), (2, 5)
To solve this, we will follow these steps −
count:= 0
n:= size of nums
for i in range 0 to n - 1, do
for j in range i+1 to n - 1, do
if nums[i] is same as nums[j], then
count := count + 1
return count
Example (Python)
Let us see the following implementation to get better understanding −
def solve(nums): count=0 n=len(nums) for i in range(n): for j in range(i+1,n): if nums[i] == nums[j]: count+=1 return count nums = [5,6,7,5,5,7] print(solve(nums))
Input
[5,6,7,5,5,7]
Output
4