algoadvance

The problem is to determine if a given integer can be reordered (by re-arranging its digits) to form a power of 2. In other words, we need to check if any permutation of the number’s digits can form a power of 2.

Example:

Clarifying Questions

  1. What is the range of n?
    • Typically, constraints are as follows: (1 \leq n \leq 10^9).
  2. Is n always a positive integer?
    • Yes, given the constraints it’s always a positive integer.
  3. What about leading zeros in the permutations?
    • Leading zeros are not considered. For example, for n = 10, “01” isn’t a valid sequence.

Strategy

To solve this problem, our approach will be:

  1. Generate All Powers of 2: We know that powers of 2 grow exponentially and quickly exceed the limit of (10^9). We will precompute all powers of 2 up to (10^9).

  2. Comparison Using Frequency Counter: For each power of 2 within our computed list, we will compare its frequency of digits (using a counter) with the digit frequency of our given number. If any of them match, it means the number can be rearranged to form that power of 2.

  3. Implementation: Using Python’s collections.Counter will facilitate the frequency count operations efficiently.

Code

Here is the Python code implementing the strategy:

from collections import Counter

def reorderedPowerOf2(n: int) -> bool:
    # Generate powers of 2 up to 2^30, since 2^30 is the largest power of 2 less than 10^9
    powers_of_2 = [str(1 << i) for i in range(31)]
    
    # Create a frequency counter for the digits of the given number n
    n_counter = Counter(str(n))
    
    # Compare digit frequency of n with each power of 2
    for power in powers_of_2:
        if n_counter == Counter(power):
            return True
    
    return False

# Example Usage
n = 46
print(reorderedPowerOf2(n))  # Output: True (because 46 can be reordered to 64, which is 2^6)

Time Complexity

Thus, the overall time complexity is approximately (O(31d) = O(d)), which simplifies to (O(1)) for practical purposes because (d) is bounded and small.

This approach ensures both efficiency and correctness for the given problem constraints.

Try our interview co-pilot at AlgoAdvance.com