Skip to main content

Number of Good Pairs

LeetCode 1635 | Difficulty: Easy​

Easy

Problem Description​

Given an array of integers nums, return *the number of good pairs*.

A pair (i, j) is called good if nums[i] == nums[j] and i < j.

Example 1:

Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.

Example 2:

Input: nums = [1,1,1,1]
Output: 6
Explanation: Each pair in the array are good.

Example 3:

Input: nums = [1,2,3]
Output: 0

Constraints:

- `1 <= nums.length <= 100`

- `1 <= nums[i] <= 100`

Topics: Array, Hash Table, Math, Counting


Approach​

Hash Map​

Use a hash map for O(1) average lookups. Store seen values, frequencies, or indices. The key question: what should I store as key, and what as value?

When to use

Need fast lookups, counting frequencies, finding complements/pairs.

Mathematical​

Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.

When to use

Problems with clear mathematical structure, counting, number properties.


Solutions​

Solution 1: C# (Best: 76 ms)​

MetricValue
Runtime76 ms
Memory37.2 MB
Date2021-12-29
Solution
public class Solution {
public int NumIdenticalPairs(int[] nums) {
int[] times = new int[101];
for (int i = 0; i < nums.Length; i++)
{
times[nums[i]]++;
}
int count = 0;
for (int i = 0; i < 101; i++)
{
if(times[i] <= 1) continue;
int pairs = (times[i]-1) * (times[i])/2;
count += pairs;
}
return count;
}
}

Complexity Analysis​

ApproachTimeSpace
Hash Map$O(n)$$O(n)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.
  • Hash map gives O(1) lookup β€” think about what to use as key vs value.
  • LeetCode provides 1 hint(s) for this problem β€” try solving without them first.
πŸ’‘ Hints

Hint 1: Count how many times each number appears. If a number appears n times, then n * (n – 1) // 2 good pairs can be made with this number.