Number of Good Pairs - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,1,1,3]
Output: 4
💡 Note: Good pairs are: (0,3), (0,4), (3,4), (2,5). nums[0]==nums[3]=1, nums[0]==nums[4]=1, nums[3]==nums[4]=1, nums[2]==nums[5]=3.
Example 2 — No Pairs
$ Input: nums = [1,2,3]
Output: 0
💡 Note: All elements are unique, so no good pairs exist where nums[i] == nums[j] with i < j.
Example 3 — All Same
$ Input: nums = [1,1,1,1]
Output: 6
💡 Note: All pairs are good: (0,1), (0,2), (0,3), (1,2), (1,3), (2,3). With 4 identical elements, we get 4×3/2 = 6 pairs.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 1 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Number of Good Pairs: [1,2,3,1,1,3]123113012345Find Good Pairs: (i,j) where nums[i] == nums[j] and i < j(0,3): nums[0]==nums[3]=1 ✓(0,4): nums[0]==nums[4]=1 ✓(3,4): nums[3]==nums[4]=1 ✓(2,5): nums[2]==nums[5]=3 ✓Total Good Pairs: 4
Understanding the Visualization
1
Input
Array [1,2,3,1,1,3] - find identical values at different positions
2
Process
Compare all pairs where first index < second index
3
Output
Count of good pairs: 4
Key Takeaway
🎯 Key Insight: Use frequency counting to avoid checking all pairs - for n identical elements, there are n×(n-1)/2 possible pairs
Asked in
LeetCode 15 Google 8
128.0K Views
Medium Frequency
~10 min Avg. Time
4.2K 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