Skip to content

Problem 1: Good Pairs

Course: Intro Class - DSA - chapter 5

Problem Link: https://leetcode.com/problems/number-of-good-pairs/description/

Given an array of integers nums, return the number of good pairs.

A pair (i, j) is called good if nums[i] == nums[j] and i < j.

Example 1:

Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.

Example 2:

Input: nums = [1,1,1,1]
Output: 6
Explanation: Each pair in the array aregood.

Example 3:

Input: nums = [1,2,3]
Output: 0
**Initial approach**

Let’s consider a different problem. Given a part of the array [0…i] where i can be anything, can we find how many elements are there that are equal to arr[i] in this part of the array?

We can run another loop j from 0 to i-1 and check if arr[j] = arr[i] and increase count.

Now do the above logic for all i from 1 to n-1.

💡 Lesser no of nested loops, the better the solution is

Optimal solution

Instead of running 2 loops, let’s see if we can do with one loop. We are running the loop of i. What do we need? No. of elements on the left that are equal to arr[i] right? And what are the elements on the left? It is same as the elements that we have visited in the loop till now, isn’t it 🙂?

So if we can maintain a frequency for all the elements that we have visited till now, in an array called freq, then freq[arr[i]] can be added to the ans.

Problem Link: https://leetcode.com/problems/two-sum/description/

**Solution**

The problem reduces to the above problem, instead of finding frequency of arr[i] we just need to find target - arr[i] .

**Think: **How do we handle negatives? We can have negative array values as well, how to handle them?