Number of Good Pairs

EasyHashing · Counting🧩 Hashing & CountingLeetCode #1512 ↗Updated

Problem

You are given an integer array nums. A pair of indices (i, j) is good when i < j and nums[i] == nums[j]. Return how many good pairs the array contains.
Inputnums = [1,2,3,1,1,3]Output4
Inputnums = [1,1,1,1]Output6
Inputnums = [1,2,3]Output0

1 ≤ n ≤ 100  ·  1 ≤ nums[i] ≤ 100

Try it yourself

Java
class Solution {
    public int numIdenticalPairs(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
When you reach a value that has already appeared k times, it forms exactly k new good pairs (one with each earlier copy). So keep a running count per value and add it before incrementing.
PatternHashing & Counting

Instinct Need "have I seen this before?", "how many times?" or "group things that look alike"? Trade memory for O(1) lookups with a HashMap, HashSet or int[26].

Memory hack Don't search, remember - every element checks in at the front desk, and the desk answers instantly.

Open the Hashing & Counting guide →

Approaches

Brute ForceCheck Every Pair

Time O(n2)Space O(1)

Enumerate all index pairs i < j with two nested loops and count the ones whose values match. It is the definition turned directly into code.

Java
public int numIdenticalPairs(int[] nums) {
    int pairs = 0;
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[i] == nums[j]) pairs++;
        }
    }
    return pairs;
}

Trivially correct and fine for n ≤ 100, but quadratic.

At a glance

LevelApproachTimeSpace
Brute ForceCheck Every PairO(n2)O(1)
BetterSort, then Count RunsO(n log n)O(n)
OptimalRunning Frequency CountO(n)O(V)
Common pitfalls
  • Incrementing the count before adding it — counts each element pairing with itself.
  • Counting ordered pairs (i, j) and (j, i) — doubles the answer.
  • Using int for f·(f−1)/2 on huge inputs — use long when n is large.
Interview tips
  • Say the combinatorial fact out loud: a group of size f gives C(f, 2) pairs.
  • Mention the incremental form: each arrival adds the number of earlier equals.
  • Note the bounded value range lets you use an array instead of a hash map.
Pattern
Frequency counting → when the answer depends on how many times each value has appeared so far.
My notes saved in this browser