Number of Good Pairs
LeetCode 1635 | Difficulty: Easyβ
EasyProblem 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?
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.
Problems with clear mathematical structure, counting, number properties.
Solutionsβ
Solution 1: C# (Best: 76 ms)β
| Metric | Value |
|---|---|
| Runtime | 76 ms |
| Memory | 37.2 MB |
| Date | 2021-12-29 |
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β
| Approach | Time | Space |
|---|---|---|
| Hash Map | $O(n)$ | $O(n)$ |
Interview Tipsβ
- 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.