Problem Description
Given an integer n, determine if its digits can be reordered (without leading zeros) to form a number that is a power of two. Return true if such a reordering exists, and false otherwise.
Key Insights
- The problem reduces to comparing the digit frequency of the given number with those of powers of two.
- Since reordering digits does not affect the frequency count, sort the digits of n and compare with the sorted digits of every valid power of two.
- The range of n (1 <= n <= 10^9) implies that the number of digits is limited, so there are only a constant number of candidate powers-of-two to check.
- Precompute the sorted representations of relevant powers of two and use a hash-based lookup for constant time checking.
Space and Time Complexity
Time Complexity: O(1) – Only a fixed number of candidate powers-of-two are processed (at most 30) along with sorting digits which takes O(d log d) with d being number of digits. Space Complexity: O(1) – Only constant extra space is used for storing the candidate signatures.
Solution
The solution uses the following approach:
- Convert the input integer n to a string and sort its digits.
- Precompute a list (or set) of sorted digit strings for each power of two that could possibly match the number of digits in n. Since n is at most 10^9, consider powers of two that have up to 10 digits.
- Check if the sorted digits of n exists in the precomputed set.
- Return true if a match is found and false otherwise.
The key insight is that if two numbers are permutations of each other, their sorted strings will be identical. This allows us to reduce the problem to simple string comparisons without trying all permutations.