Back to photostream

Number of Good Pairs Leetcode Solution

Problem Statement

In this problem an array of integers is given and we have to find out the count of total number of good pairs (a, a) where a=a.

Example

nums =

4

Explanation: There are 4 good pairs at indices (0,3), (0,4), (3,4), (2,5) .

 

6

Explanation: Each pair in the array are good.

Approach (Brute Force)

In the given problem we can use two loop, one for a and second for a of the pair. In this nested loop we will iterate for all possible combination for the pair (a, a) and check whether a is equal to a or not.

 

Algorithm:

 

1. Create a count variable and initialize with zero.

2. Run a nested loop, outer loop for a from i=0 to i=n-1 and inner loop for a from j=i+1 to j=n-1.

3. If a=a, add current pair to count by incrementing its value by 1.

4. Return the value of count variable.

Implementation for Number of Good Pairs Leetcode Solution

C++ Program

#include

using namespace std;

 

int numIdenticalPairs(vector& nums)

{

int res = 0;

for(int i=0;i

 

www.tutorialcup.com/leetcode-solutions/number-of-good-pai...

26 views
0 faves
0 comments
Uploaded on October 14, 2021
Taken on December 12, 2020