Number of Good Pairs
Easy
Topics
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
c times contributes c(c-1)/2.Input: nums = [1,2,3,1,1,3] Output: 4
Example 2
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
- Keep a count per value.
- 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 requiresi < 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 totalimport java.util.*;
class Solution {
public int numIdenticalPairs(int[] nums) {
Map<Integer, Integer> cnt = new HashMap<>();
int total = 0;
for (int x : nums) {
int c = cnt.getOrDefault(x, 0);
total += c;
cnt.put(x, c + 1);
}
return total;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int numIdenticalPairs(vector<int>& nums) {
unordered_map<int, int> cnt;
int total = 0;
for (int x : nums) {
total += cnt[x];
cnt[x]++;
}
return total;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var numIdenticalPairs = function(nums) {
const cnt = {};
let total = 0;
for (const x of nums) {
total += (cnt[x] || 0);
cnt[x] = (cnt[x] || 0) + 1;
}
return total;
};