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 INPUT nums = [1, 2, 3, 1, 1, 3] 1 i=0 2 i=1 3 i=2 1 i=3 1 i=4 3 i=5 Good Pairs Found: (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 ALGORITHM STEPS 1 Initialize count=0, hashmap={} 2 Iterate Array For each num in nums 3 Add to Count count += map[num] 4 Update Map map[num]++ HashMap State During Iteration: Step Num Map Count i=0 1 {1:1} 0 i=1 2 {1:1,2:1} 0 i=3 1 {1:2,...} +1 i=4 1 {1:3,...} +2 i=5 3 {...,3:2} +1 Total: 0+0+0+1+2+1 = 4 FINAL RESULT Output: 4 OK - 4 Good Pairs Found Pairs Breakdown: Value 1: 3 occurrences Pairs = 3*(3-1)/2 = 3 Value 3: 2 occurrences Pairs = 2*(2-1)/2 = 1 Total = 3 + 1 = 4 Key Insight: One Pass Optimization: Instead of checking all pairs O(n^2), we use a hashmap to count occurrences. When we see a number, all its previous occurrences form good pairs with it. Add count to result, then increment the count. Time: O(n), Space: O(n). This avoids redundant pair comparisons! TutorialsPoint - Number of Good Pairs | One Pass Count - Optimized
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