AlgoMaster Logo

Number of Good Pairs

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The simplest approach is to check every possible pair (i, j) where 0 <= i < j < nums.length and check if they are equal. If they are, we have found a "good pair."

Steps:

  1. Initialize a counter count to zero to keep track of good pairs.
  2. Use two nested loops, the outer loop (i) goes from 0 to nums.length - 1, and the inner loop (j) runs from i+1 to nums.length - 1.
  3. For each pair (i, j), check if nums[i] == nums[j]. If yes, increment the count.
  4. Return the count after both loops have finished.

Code:

2. HashMap

Intuition:

Instead of comparing pairs directly (which would take O(n²) time), we can count how many times each number appears using a HashMap. Every time we encounter a number we've already seen, it forms a “good pair” with all its previous occurrences.

If a number appears n times, the total number of good pairs formed by that number is:

But rather than using the formula at the end, we can compute pairs incrementally as we traverse the array:

  • When the first occurrence arrives → contributes 0 pairs
  • Second occurrence → contributes 1 new pair
  • Third occurrence → contributes 2 new pairs
  • Fourth occurrence → contributes 3 new pairs
  • … and so on

So when we encounter a number again, we simply add its current frequency to the answer.

Steps:

  1. Use a HashMap to store the frequency of each number in the array.
  2. Iterate through the array, updating the frequency of each number in the HashMap.
  3. For each number encountered again, increment the count of good pairs using the formula for combinations since each new occurrence can pair with all previous ones.
  4. Return the total count of good pairs.

Code: