Problem · Array

Count Valid Bitwise Pairs

Learn this problem
MediumStripe logoStripeFULLTIMENEW GRADOA
See Stripe hiring insights

Problem statement

Stripe's analytics team is studying relationships between values stored in an array.

Given an array A of N non-negative integers and a non-negative integer K, determine the number of index pairs (i, j) such that 1 <= i < j <= N and:

3(A_i | A_j) - (A_i & A_j) - A_i - A_j + (A_i XOR A_j)^2 - ((A_i | A_j) - (A_i & A_j))^2 + (A_i XOR A_j) + (A_i & A_j) + (A_i | A_j) = K + A_j + 2(A_i XOR A_j)

Here |, &, and XOR denote bitwise OR, AND, and XOR. Return the total number of valid pairs.

Equivalent condition

Using the standard bitwise identities A_i | A_j = (A_i & A_j) + (A_i XOR A_j) and A_i + A_j = (A_i | A_j) + (A_i & A_j), the source equation simplifies to:

A_i + (A_i XOR A_j) = K

The order remains important: A_i is the earlier value because the source requires i < j.

Original input and output format

The source uses T test cases. Each case contains N, K, and the array A, and outputs one count. The FastPrep function below represents one source test case.

Function

countValidBitwisePairs(A: long[], K: long) → long

Examples

Example 1

A = [1,2,3]K = 4return = 1

The pair at 1-based indices (1, 2) is valid because 1 + (1 XOR 2) = 4. The other two pairs produce 3.

Example 2

A = [0,15]K = 15return = 1

The only pair is valid: 0 + (0 XOR 15) = 15.

Example 3

A = [15,0]K = 15return = 0

The condition is asymmetric. Here 15 + (15 XOR 0) = 30, so reversing the values from Example 2 changes the answer to zero.

Constraints

  • For the FastPrep one-case interface, 1 <= A.length <= 10^5.
  • 0 <= K <= 10^18.
  • 0 <= A[i] <= 10^18.
  • In the source batch format, 1 <= T <= 200 and the sum of N over all test cases does not exceed 3 * 10^5.

More Stripe problems

drafts saved locally
public long countValidBitwisePairs(long[] A, long K) {
  // write your code here
}
A[1,2,3]
K4
expected1
checking account