#1512

Number of Good Pairs

Easy Counting

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Count pairs of indexes (i, j) with i < j where nums[i] equals nums[j].

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: count pairs of equal values (i before j).

Why this works: when a value appears for the k-th time, it makes a new pair with each of the k-1 earlier copies. Keep a count per value and add it before increasing.

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

1: seen 0 before → +0   (seen[1]=1)2: +0, 3: +01: seen 1 before → +1   (seen[1]=2)1: seen 2 before → +2   (seen[1]=3)3: seen 1 before → +1total = 4

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Incrementing the count before adding it, which counts each element as a pair with itself.