BINSHFFL - Editorial

Problem Link - Binary Shuffle

Problem Statement

Chef has two integers A and B. He can perform the following operation on A an arbitrary number of times (including zero):

  • write A as a binary number with an arbitrary number of leading zeroes (possibly without any)
  • shuffle the binary digits of A in an arbitrary way, obtaining a number s
  • replace A by s+1

Chef is wondering about the minimum number of operations he has to perform on A in order to obtain B. Compute this number or determine that it is impossible.

Approach

The code idea is to determine how many operations are needed to transform A into B based on their binary representations. It first checks if A is equal to B. If they are equal, the answer is 0, meaning no operations are needed.

Next, the code handles special cases:

  1. If B=0, it’s impossible to reach 0 from any positive A (since the operations will always yield at least 1), so the answer is -1.

  2. If B=1:

    • If A=0, one operation is required to reach 1 by transforming 0 to 1.
    • If A \neq 0, it’s impossible to reach 1 from any non-zero A, resulting in an answer of -1.

For other values of B, the code counts the number of set bits (1s) in both A and B−1 (using the __builtin_popcountll function). Let aa be the count of 1s in A, and bb be the count of 1s in B−1.

Time Complexity

The time complexity is O(\log(\text{max}(A, B))) due to the operations on the binary representations of A and B.

Space Complexity

The space complexity is O(1) because the solution uses a constant amount of space for variables.