1525. Matching Popcount Pairs
A warehouse tags each crate with a non-negative integer code stored in the array nums. Two crates are called twins when their codes contain the same number of set bits in binary, for example 3 (11) and 5 (101) are twins, while 7 and 8 are not. The values themselves do not need to be equal.
Return the number of index pairs (i, j) with i < j such that nums[i] and nums[j] are twins. Group the crates by their bit count and, for a group of size c, add c*(c-1)/2. The answer can reach almost half a million, so return it as a 64-bit integer. Target O(n) time and O(1) extra space, since bit counts never exceed 31.
Example 1
- Input:
- nums = [3,5,7,8]
- Output:
- 1
- Explanation:
3 and 5 both have two set bits, and 7 and 8 have different counts, so exactly one pair.
Example 2
- Input:
- nums = [1,2,4,8]
- Output:
- 6
- Explanation:
All four values have one set bit, which gives 4*3/2 = 6 pairs.
Constraints
1 ≤ n ≤ 1000; 0 ≤ nums[i] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n)
- Space
- O(1)