Reordered Power of 2 - Problem
Given an integer n, your task is to determine if we can rearrange its digits to form a power of 2.
You can reorder the digits in any order (including keeping the original order), but the resulting number cannot have leading zeros. Return true if such a rearrangement is possible, false otherwise.
Examples:
n = 1→true(1 is 20)n = 10→false(digits 1,0 cannot form any power of 2)n = 16→true(16 is 24)n = 24→false(digits 2,4 cannot form any power of 2)
The challenge is to efficiently check if any permutation of the digits can create a power of 2 without generating all possible permutations.
Input & Output
example_1.py — Basic Power of 2
$
Input:
n = 1
›
Output:
true
💡 Note:
1 is already a power of 2 (2^0 = 1), so no rearrangement is needed.
example_2.py — Simple Rearrangement
$
Input:
n = 46
›
Output:
true
💡 Note:
We can rearrange 46 to get 64, which is 2^6. The digits 4 and 6 can form the power of 2: 64.
example_3.py — Impossible Case
$
Input:
n = 24
›
Output:
false
💡 Note:
No rearrangement of digits 2 and 4 can form a power of 2. The only possibilities are 24 and 42, neither of which is a power of 2.
Visualization
Tap to expand
Understanding the Visualization
1
Count Your Tiles
Count how many of each digit you have in the input number
2
Check Dictionary
Go through powers of 2 and count their digits
3
Compare Counts
If any power of 2 has the same digit counts, we found a match
4
Return Result
Return true if match found, false otherwise
Key Takeaway
🎯 Key Insight: Instead of generating O(n!) permutations, we use digit frequency counting which reduces the problem to comparing O(1) sized arrays for O(log n) powers of 2.
Time & Space Complexity
Time Complexity
O(log n)
Only need to check powers of 2 with same digit count, which is logarithmic
⚡ Linearithmic
Space Complexity
O(1)
Fixed-size frequency arrays (10 elements for digits 0-9)
✓ Linear Space
Constraints
- 1 ≤ n ≤ 109
- The input number can have up to 10 digits
- No leading zeros allowed in the rearranged number
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code