Reordered Power of 2 (LeetCode 869): Solution and Explanation

Medium
Hash Table
Math
Sorting
Counting
Enumeration

Given an integer n, decide whether its digits can be rearranged, without a leading zero, into a power of two.

Intuition

The literal approach generates every permutation of the digits and tests each one. A 10 digit number has up to 3.6 million orderings, which is slow and also pointless, because the question is really about which digits n has, not their order.

Any rearrangement keeps the same multiset of digits. Sorting the digits turns that multiset into a short string, a fingerprint that every rearrangement of n shares and no other digit multiset has.

Now flip the search around. Instead of building numbers from n's digits and checking if they are powers of two, list the powers of two and check if any of them has n's fingerprint. Since n is at most 10^9, only 2^0 through 2^30 can qualify. That is 31 candidates.

The leading zero rule takes care of itself. If a power of two matches the fingerprint, that power is itself a valid arrangement of n's digits, and a power of two never starts with 0.

Approach: Sorted digit fingerprint

  1. Compute target, the digits of n sorted in ascending order.
  2. For each k from 0 to 30, compute the sorted digits of 2^k.
  3. If they equal target, return true.
  4. After all 31 checks fail, return false.

Step-by-step example

n = 46
  1. target = sorted("46") = "46".
  2. 2^0 = 1 through 2^3 = 8 have one digit, so their fingerprints cannot match a two digit target.
  3. 2^4 = 16 sorts to "16" and 2^5 = 32 sorts to "23". Neither equals "46".
  4. 2^6 = 64 sorts to "46", which matches. Return true: 46 can be rearranged into 64.

Code: Python, Java, C++

1class Solution:
2    def reorderedPowerOf2(self, n: int) -> bool:
3        target = sorted(str(n))
4        for k in range(31):
5            if sorted(str(1 << k)) == target:
6                return True
7        return False
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(1)

There are always 31 candidates, and each fingerprint sorts at most 10 digits, so the work does not grow with n beyond its digit count.

Space

O(1)

Each fingerprint is a string of at most 10 characters.

Other approaches

Try every permutation (time O(d! * d), space O(d))

Generate each ordering of the digits, skip ones with a leading zero, and test x & (x - 1) == 0. It is correct but explores up to 10! orderings.

Digit count arrays (time O(1), space O(1))

Instead of sorting, count how many times each digit 0 to 9 appears and compare the count arrays. It is the same idea with a 10 slot array as the fingerprint.

Common mistakes

  • Generating permutations. It works for small inputs but is wasteful and easy to get wrong with repeated digits.
  • Checking powers beyond 2^30 with 32 bit integers. 1 << 31 overflows to a negative number in Java, C++ and C#.
  • Comparing the numbers instead of their digit multisets. 46 is not 64; the fingerprints are what must match.
  • Worrying about leading zeros. A matching power of two never has one, so no extra check is needed.

Frequently asked questions

Why do only 31 powers of two need checking?

A rearrangement keeps the digit count of n. Apart from 1,000,000,000 itself, whose digits match no power of two, every allowed n has at most 9 digits, and the powers of two with at most 9 digits stop at 2^29. Looping k from 0 to 30 covers all of them and stays inside the signed 32 bit range.

Can I compare digit counts instead of sorted strings?

Yes. Counting digits 0 to 9 into an array and comparing arrays is equivalent and avoids sorting. Some solutions even encode the counts as a single number.

What is the time complexity?

Constant: 31 candidates, each with at most 10 digits to sort or count.