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 = 1true (1 is 20)
  • n = 10false (digits 1,0 cannot form any power of 2)
  • n = 16true (16 is 24)
  • n = 24false (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
Your Tiles: 4, 646Count: 4→1, 6→1Dictionary (Powers of 2)16: 1→1, 6→132: 3→1, 2→164: 6→1, 4→1128: 1→1, 2→1, 8→1✓ Match!TRUE
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

n
2n
Linearithmic
Space Complexity
O(1)

Fixed-size frequency arrays (10 elements for digits 0-9)

n
2n
Linear Space

Constraints

  • 1 ≤ n ≤ 109
  • The input number can have up to 10 digits
  • No leading zeros allowed in the rearranged number
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
52.0K Views
Medium Frequency
~15 min Avg. Time
1.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen