#2354
Hard Algorithms Number of excellent pairs
Array Hash Table Binary Search Bit Manipulation
49.0% acceptance
Feb 25, 2026
619
25
You are given a 0-indexed positive integer array nums and a positive integer k.
A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied:
Both the numbers num1 and num2 exist in the array nums.
The sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equal to k, where OR is the bitwise OR operation and AND is the bitwise AND operation.
Return the number of distinct excellent pairs.
Two pairs (a, b) and (c, d) are considered distinct if either a != c or b != d. For example, (1, 2) and (2, 1) are distinct.
Note that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least one occurrence of num1 in the array.
Solution
Rust
Time O(n log n)
Space O(1)
use std::collections::HashSet;
impl Solution {
pub fn count_excellent_pairs(nums: Vec<i32>, k: i32) -> i64 {
let distinct: HashSet<i32> = nums.into_iter().collect();
let mut pc: Vec<i32> = distinct.iter().map(|&n| n.count_ones() as i32).collect();
pc.sort_unstable();
let n = pc.len();
let mut ans = 0i64;
for i in 0..n {
let need = k - pc[i];
let j = pc.partition_point(|&x| x < need);
ans += (n - j) as i64;
}
ans
}
}