Number of Good Pairs (LeetCode 1512): Solution and Explanation
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 exist.
Intuition
The obvious solution checks every pair with two nested loops. With at most 100 elements that is fine, but it hides a simple counting idea that turns the problem into one pass.
Look at a good pair from its right end. When the scan reaches index j holding value x, the good pairs that end at j are exactly the earlier positions that also hold x. If three earlier elements equal x, index j closes three new pairs.
So keep a running count for each value. At every element, add the current count of its value to the answer, then increment that count so later copies will pair with this one too. Every pair is counted exactly once, at the moment its second element arrives.
Approach: One pass with a count per value
- Create an empty map
countfrom value to how many times it has appeared so far, and setpairs = 0. - For each element
xinnums, addcount[x]topairs. Those are the good pairs that end at this element. - Then increment
count[x], so this element is available to pair with later copies ofx. - After the loop, return
pairs.
Step-by-step example
nums = [1,2,3,1,1,3]
- Index 0 holds 1. count[1] is 0, so no pair. count[1] becomes 1.
- Index 1 holds 2 and index 2 holds 3. Neither has an earlier copy, so pairs stays 0. count[2] and count[3] become 1.
- Index 3 holds 1. count[1] is 1, so pair (0,3) is found and pairs = 1. count[1] becomes 2.
- Index 4 holds 1. count[1] is 2, so pairs (0,4) and (3,4) are found and pairs = 3. count[1] becomes 3.
- Index 5 holds 3. count[3] is 1, so pair (2,5) is found and pairs = 4. The answer is 4.
Code: Python, Java, C++
1class Solution:
2 def numIdenticalPairs(self, nums: List[int]) -> int:
3 count = {}
4 pairs = 0
5 for x in nums:
6 pairs += count.get(x, 0)
7 count[x] = count.get(x, 0) + 1
8 return pairs1class Solution {
2 public int numIdenticalPairs(int[] nums) {
3 int[] count = new int[101];
4 int pairs = 0;
5 for (int x : nums) {
6 pairs += count[x];
7 count[x]++;
8 }
9 return pairs;
10 }
11}1class Solution {
2public:
3 int numIdenticalPairs(vector<int>& nums) {
4 vector<int> count(101, 0);
5 int pairs = 0;
6 for (int x : nums) {
7 pairs += count[x];
8 count[x]++;
9 }
10 return pairs;
11 }
12};Time and space complexity
O(n)
Each element is visited once, with one lookup and one update in the count map.
O(k)
The map holds one counter per distinct value, at most n entries. With values limited to 1..100 a fixed array of 101 counters also works.
Other approaches
Check every pair (time O(n^2), space O(1))
Two nested loops over i < j, counting the pairs whose values match. Simple and fast enough for n = 100, but it does quadratic work.
Count first, then use the formula (time O(n), space O(k))
Count how often each value appears, then add c * (c - 1) / 2 for every count c, which is the number of ways to choose two of the c positions. It gives the same total as the running count.
Sort and count runs (time O(n log n), space O(n))
Sort a copy of the array so equal values sit together, then apply the pair formula to each run length. Sorting costs more than counting and is unnecessary here.
Common mistakes
- Incrementing the count before adding it. That makes every element pair with itself and overcounts by n.
- Counting both (i, j) and (j, i). A good pair needs i < j, so each unordered pair counts once. Counting at the later index handles this automatically.
- Using the formula c * c / 2 or c * (c + 1) / 2 instead of c * (c - 1) / 2 when counting in a second pass.
- Indexing a fixed array of size 100 with values that can be 100. Values go up to 100, so the array needs 101 slots.
Frequently asked questions
Why add the count before incrementing it?
The count before the update is the number of earlier copies, which is exactly the number of pairs the current element closes. Incrementing first would include the element itself and create a pair (j, j).
Is the running count the same as c * (c - 1) / 2?
Yes. A value that appears c times adds 0 + 1 + 2 + ... + (c - 1) over the scan, and that sum equals c * (c - 1) / 2.
Can the answer overflow?
No. With n at most 100 the largest answer is 100 * 99 / 2 = 4950, when every element is equal.
How does this connect to harder counting problems?
The same idea, counting matches with earlier elements through a hash map in one pass, solves Two Sum and Subarray Sum Equals K, where you look up a complement or a prefix sum instead of the value itself.