Number of Excellent Pairs LeetCode solution in Java
1class Solution {2public long countExcellentPairs(int[] nums, int k) {3HashMap<Integer, Set<Integer>> map = new HashMap<>();4for (int i : nums) {5int x = Integer.bitCount(i);6map.putIfAbsent(x, new HashSet<>());7map.get(x).add(i);8}9long ans = 0;10HashSet<Integer> vis = new HashSet<>();11for (int i : nums) {12if (vis.contains(i)) continue;13int need = Math.max(0, k - Integer.bitCount(i));14for (int key : map.keySet()) // runs at max 30 times15if (key >= need) ans += (long) map.get(key).size();16vis.add(i);17}18return ans;19}20}