#869

Reordered Power of 2

Medium
Hash TableMathSortingCountingEnumerationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n!)
O(n log n)
Space
O(n)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

Instead of generating permutations, we can precompute all powers of two up to 2^30 and compare the sorted digit representation of the input number with these precomputed values. This is much more efficient.

⚙️

Algorithm

3 steps
  1. 1Step 1: Precompute all powers of two from 2^0 to 2^29 and store their sorted digit representations.
  2. 2Step 2: Convert the input number n into a sorted string of its digits.
  3. 3Step 3: Check if the sorted digit representation of n matches any of the precomputed powers of two.
solution.py6 lines
1# Full working Python code
2import itertools
3
4def reorderedPowerOf2(n):
5    powers_of_two = sorted([''.join(sorted(str(1 << i))) for i in range(30)])
6    return ''.join(sorted(str(n))) in powers_of_two

Complexity note: The time complexity is O(n log n) due to sorting the digits of n, and the space complexity is O(n) for storing the sorted representations of powers of two.

  • 1Powers of two have unique digit patterns.
  • 2Sorting is a powerful tool for comparison.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.