Number of Good Pairs - Problem

Given an array of integers nums, your task is to count the number of "good pairs" in the array.

A pair (i, j) is considered good if:

  • nums[i] == nums[j] (the values are equal)
  • i < j (the first index comes before the second)

For example, in the array [1,2,3,1,1,3], we have:

  • Indices 0 and 3: nums[0] = nums[3] = 1
  • Indices 0 and 4: nums[0] = nums[4] = 1
  • Indices 3 and 4: nums[3] = nums[4] = 1
  • Indices 2 and 5: nums[2] = nums[5] = 3

That's 4 good pairs total!

Your goal: Return the total count of good pairs in the given array.

Input & Output

example_1.py — Python
$ Input: [1,2,3,1,1,3]
Output: 4
💡 Note: There are 4 good pairs: (0,3), (0,4), (3,4), (2,5). Each pair satisfies nums[i] == nums[j] and i < j.
example_2.py — Python
$ Input: [1,1,1,1]
Output: 6
💡 Note: All pairs are good pairs: (0,1), (0,2), (0,3), (1,2), (1,3), (2,3). With 4 identical elements, we get 4×3/2 = 6 pairs.
example_3.py — Python
$ Input: [1,2,3]
Output: 0
💡 Note: No two elements are equal, so there are no good pairs.

Visualization

Tap to expand
One-Pass Hash Table SolutionInput: [1,2,3,1,1,3]Step 1: Process element 1 (index 0)freq[1] = 0, so add 0 pairs. Update freq[1] = 1. Total pairs = 0💡 First occurrence of 1, no previous matchesStep 4: Process element 1 (index 3)freq[1] = 1, so add 1 pair. Update freq[1] = 2. Total pairs = 1💡 Second occurrence of 1, pairs with the first oneStep 5: Process element 1 (index 4)freq[1] = 2, so add 2 pairs. Update freq[1] = 3. Total pairs = 3💡 Third occurrence of 1, pairs with both previous onesStep 6: Process element 3 (index 5)freq[3] = 1, so add 1 pair. Update freq[3] = 2. Total pairs = 4💡 Second occurrence of 3, pairs with the first oneFINAL4PAIRS
Understanding the Visualization
1
Start Fresh
Begin with an empty frequency counter and pairs count of 0
2
Process Each Element
For each element, add its current frequency to pairs count, then increment frequency
3
Count Incrementally
This works because the nth occurrence of a value can pair with all n-1 previous occurrences
Key Takeaway
🎯 Key Insight: Instead of comparing all pairs, we count incrementally. Each element can only pair with identical elements we've seen before, making the solution both elegant and efficient.

Time & Space Complexity

Time Complexity
⏱️
O(n)

Single pass through the array, with O(1) hash map operations on average

n
2n
Linear Growth
Space Complexity
O(n)

Hash map stores at most n entries in worst case (all elements unique)

n
2n
Linearithmic Space

Constraints

  • 1 ≤ nums.length ≤ 100
  • 1 ≤ nums[i] ≤ 100
  • The array contains only positive integers
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
98.5K Views
High Frequency
~5 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen