1527. Even Parity Pairs

Easy1.5 points estimatedBit ManipulationBrainteaserCounting

A signal processor receives a list of non-negative integer words in the array nums. It compares two words by XOR-ing them and looking at the number of set bits in the result: the pair is calm when that number is even and noisy when it is odd. Checking every pair directly would work but wastes effort.

Return how many index pairs (i, j) with i < j are calm. Observe that the XOR of two numbers has an even number of set bits exactly when the two numbers have bit counts of the same parity, so it is enough to count the words with even bit count and the words with odd bit count and combine the two group sizes. Return the answer as a 64-bit integer. Target O(n) time and O(1) extra space.

Example 1

Input:
nums = [1,2,3]
Output:
1
Explanation:

1 and 2 each have odd popcount, 3 has even, so only the pair (1,2) is calm.

Example 2

Input:
nums = [0,3,5,6]
Output:
6
Explanation:

All four values have even popcount, giving 4*3/2 = 6 calm 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)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…