1540. Nth Disjoint Mask

Medium3.5 points estimatedBit ManipulationBitmask

A locker system uses x as a mask of switches that are permanently jammed in the ON position. A new setting y (a non-negative integer) is allowed only if it never turns on a jammed switch, that is, y & x == 0.

List all allowed settings in increasing order, starting with 0 as the first one. Return the k-th allowed setting. For example, with x = 5 (binary 101) the allowed settings are 0, 2, 8, 10, 16, ..., so for k = 3 the answer is 8.

There are infinitely many allowed settings because bits above the highest jammed one are always free. Do not iterate through candidates: the order of allowed settings matches the order of the numbers k - 1 written in binary, with each of its bits placed into the free positions of x from low to high. Run in time proportional to the number of bits and use constant space. The result can exceed 32 bits.

Example 1

Input:
x = 5, k = 3
Output:
8
Explanation:

Allowed settings for x = 5 are 0, 2, 8, 10, so the third is 8.

Example 2

Input:
x = 6, k = 4
Output:
9
Explanation:

For x = 6 the allowed settings are 0, 1, 8, 9, so the fourth is 9.

Constraints

0 ≤ x < 220; 1 ≤ k ≤ 220 (the answer is below 241)

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 k + log x)
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…