Reordered Power of 2 - Problem

You are given an integer n. We can reorder the digits of n in any order (including the original order) such that the leading digit is not zero.

Return true if and only if we can do this so that the resulting number is a power of two.

Input & Output

Example 1 — Basic Case
$ Input: n = 1
Output: true
💡 Note: 1 is already a power of 2 (2⁰ = 1), so no reordering needed
Example 2 — Reordering Required
$ Input: n = 46
Output: true
💡 Note: We can reorder 46 to get 64, which is 2⁶ = 64
Example 3 — No Valid Arrangement
$ Input: n = 24
Output: false
💡 Note: No arrangement of digits 2,4 can form a power of 2 (42 and 24 are both not powers of 2)

Constraints

  • 1 ≤ n ≤ 109

Visualization

Tap to expand
Reordered Power of 2 Pre-computed Powers Lookup Approach INPUT n = 1 Integer Input Digit Analysis 1 Digit Count: [0,1,0,0,0,0,0,0,0,0] Index 1 has count 1 (one digit '1') ALGORITHM STEPS 1 Pre-compute Powers Generate all 2^k for k=0..30 2 Count Digits Create digit frequency array 3 Compare Signatures Match against power of 2 4 Return Result True if match found Power of 2 Lookup Table 2^0 = 1 [0,1,0,0,0,0,0,0,0,0] 2^1 = 2 [0,0,1,0,0,0,0,0,0,0] 2^2 = 4 [0,0,0,0,1,0,0,0,0,0] 2^3 = 8 [0,0,0,0,0,0,0,0,1,0] ... 2^30 = 1073741824 FINAL RESULT Match Found! n = 1 digits: [1] = 2^0 = 1 digits: [1] Output: true 1 is a power of 2 The digit signature of n=1 matches the signature of 2^0 = 1 exactly. OK Key Insight: Two numbers are anagrams of each other if and only if they have the same digit frequency signature. By pre-computing signatures of all powers of 2 (up to 2^30), we can check in O(1) if any reordering works. TutorialsPoint - Reordered Power of 2 | Pre-computed Powers Lookup Approach
Asked in
Google 12 Facebook 8 Microsoft 6
28.0K Views
Medium Frequency
~15 min Avg. Time
892 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