[
sort
counter
math
anagram
]
Leetcode 0869. Reordered Power of 2
https://leetcode.com/problems/reordered-power-of-2
This is in fact question about anagrams: given string we need to find if we have another string from list of powers of too, which is anagram of original string. Let us iterate through all powers of two and check if count of this number is equal to count of given number N
.
Complexity: time complexity will be O(log^2 N)
: we check O(log N)
numbers, each of them have O(log N)
digits at most. In fact it can be improved to O(log^2N)
, because there can be at most 4
numbers with given number of digits, but here it just not worth it. Space complexity is O(log N)
.
class Solution:
def reorderedPowerOf2(self, N):
cnt = Counter(str(N))
return any(cnt == Counter(str(1<<i)) for i in range(30))
If you like the solution, you can upvote it on leetcode discussion section: Problem 0869