1566. Carry-Free Pairs

Two engineers each pick a switch-panel setting, which is any integer from 0 to n inclusive. A pair of settings (a, b) is clean when adding the two numbers produces no carry in binary, that is, a + b equals a ^ b (equivalently, no bit position is set in both numbers).

Count the ordered pairs (a, b) with 0 <= a, b <= n that are clean, and return the count as a long. Pairs (a, b) and (b, a) are different unless a = b, and (0, 0) counts as a clean pair.

Checking every pair needs O(n^2) time and is far too slow for large n. The intended solution is a digit DP over the bits of n from the top, tracking two flags that say whether a and b still match the prefix of n. Target O(log n) time and O(1) space.

Example 1

Input:
n = 0
Output:
1
Explanation:

Only the pair (0, 0) exists.

Example 2

Input:
n = 2
Output:
7
Explanation:

The clean pairs are (0,0), (0,1), (0,2), (1,0), (1,2), (2,0) and (2,1), seven in total.

Example 3

Input:
n = 5
Output:
21
Explanation:

Counting all pairs of 0..5 with no shared set bit gives 21.

Constraints

0 ≤ n ≤ 109 (answer < 253)

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(log 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…