#1512
Easy Algorithms Number of good pairs
Array Hash Table Math Counting
89.8% acceptance
Feb 25, 2026
5850
286
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.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn num_identical_pairs(nums: Vec<i32>) -> i32 {
let mut count = std::collections::HashMap::new();
let mut ans = 0;
for x in nums {
let c = count.entry(x).or_insert(0);
ans += *c;
*c += 1;
}
ans
}
}