Number of Good Pairs

Easy

Topics
ArrayHash TableMath

Given an array nums, a pair (i, j) is good if nums[i] == nums[j] and i < j. Return the number of good pairs.

Example 1

102132131435
value appears more than once
A good pair is two equal values at different indices. Equivalently, a value seen c times contributes c(c-1)/2.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [1,2,3,1,1,3]
Output: 4

Example 2

10111213
value appears more than once
Input:  nums = [1,1,1,1]
Output: 6

Constraints

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

A good pair is two equal values at different indices. The double loop over all pairs is O(n^2) and fine at these constraints, but the structure is better seen by counting.

If a value occurs k times, it contributes k choose 2 = k(k-1)/2 pairs. So one counting pass followed by that formula per distinct value is O(n).

Neater still, and what the shown solution does: as you sweep, each element pairs with every earlier equal element. So add the running count of that value before incrementing it. That accumulates the same total in one pass with no second loop over the counts.

Approach

  1. Keep a count per value.
  2. For each element: add the current count of that value to the answer, then increment the count.

Dry Run

nums = [1,2,3,1,1,3]

x=1  seen 0 of them -> total 0   count{1:1}
x=2  seen 0         -> total 0   count{1:1,2:1}
x=3  seen 0         -> total 0   count{...,3:1}
x=1  seen 1         -> total 1   count{1:2,...}
x=1  seen 2         -> total 3   count{1:3,...}
x=3  seen 1         -> total 4   count{3:2,...}

answer 4

cross-check with the formula: value 1 appears 3 times -> 3,
value 3 appears twice -> 1, total 4  ✓

Complexity

  • Time — O(n): one pass with constant-time map operations, against O(n^2) for enumerating pairs.
  • Space — O(n) for the counts in general; here the values are bounded by 100, so it is O(1) under the fixed-range convention — a 101-slot array would make that explicit.

Common Pitfalls

  • Incrementing the count before adding it, which counts each element as a pair with itself.
  • Using k * (k-1) without halving, double-counting every pair.
  • Counting ordered pairs. (i, j) and (j, i) are the same pair, and the problem requires i < j.
  • Sorting first to group equal values. It works but is O(n log n) and unnecessary.

Full Solution — all languages

class Solution:
    def numIdenticalPairs(self, nums):
        cnt = {}
        total = 0
        for x in nums:
            total += cnt.get(x, 0)
            cnt[x] = cnt.get(x, 0) + 1
        return total
SensAI
Beta
Tap the mic to stop voice mode