Introduction
So here we are given an array. We have have to find how many pairs have the equal value like, nums = [1,2,3,1,1,3] and There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
Examples
Steps
- Take a nested for loop
- 1st loop runs 0 to nums.length.
- 2nd loop starts from first loop index+1 and ends to nums.length.
- if (nums[i] == nums[j]), counter++
- return counter.
JavaCode
class Solution {
public int numIdenticalPairs(int[] nums) {
int counter = 0;
for(int i =0; i<nums.length; i++){
for(int j = i+1; j<nums.length; j++){
if( nums[i] == nums[j]){
counter++;
}
}
}
return counter;
}
}
Top comments (0)