DEV Community

Cover image for 1512. Number of Good Pairs
Tahzib Mahmud Rifat
Tahzib Mahmud Rifat

Posted on

1512. Number of Good Pairs

Introduction

Image description

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

Image description

Steps

  1. Take a nested for loop
  2. 1st loop runs 0 to nums.length.
  3. 2nd loop starts from first loop index+1 and ends to nums.length.
  4. if (nums[i] == nums[j]), counter++
  5. 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;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Top comments (0)