You are 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: 4Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
Example 2:
Input: nums = [1,1,1,1]
Output: 6Explanation: Each pair in the array are good.
Example 3:
Input: nums = [1,2,3]
Output: 0Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100Before attempting this problem, you should be comfortable with:
A good pair is defined as a pair (i, j) where i < j and nums[i] == nums[j]. The simplest approach is to check every possible pair of indices and count those that satisfy both conditions.
res to zero.i, and the inner loop picks index j where j > i.nums[i] == nums[j], increment res.res.If a value appears c times, the number of good pairs using that value equals the number of ways to choose 2 indices from c positions, which is c * (c - 1) / 2. We can count frequencies first, then sum up the pairs for each value.
c, add c * (c - 1) / 2 to the res.Instead of counting all frequencies first and then computing pairs, we can count pairs on the fly. As we traverse the array, each new occurrence of a value can form a good pair with every previous occurrence of that same value. We track the count of each value seen so far and add it to the res before updating the count.
res (this is the number of new pairs formed).res.A good pair requires i < j, meaning each pair should only be counted once. When using nested loops, ensure the inner loop starts from i + 1 rather than 0. Similarly, when using the mathematical formula c * (c - 1) / 2, this already accounts for unique pairs and should not be doubled.
When using the formula c * (c - 1) / 2 to calculate the number of pairs for a frequency c, the multiplication can overflow for large values if using 32-bit integers. In languages with fixed-size integers, ensure you use an appropriate data type or perform the division before the multiplication becomes too large.
Sign in to join the discussion