Suppose we have an array of called nums whose length is even, we have to check whether it is possible to reorder it in such a way that nums[2*i + 1] = 2*nums[2*i] for every 0 <= i < size of nums/2.
So, if the input is like nums = [4,-2,2,-4], then the output will be True.
To solve this, we will follow these steps −
cnt := a map containing all elements in nums and their frequency values
for each x in the sorted list cnt which is sorted based on their absolute values, do
if cnt[x] > cnt[2 * x], then
return False
cnt[2 * x] := cnt[2 * x] - cnt[x]
return True
Example
Let us see the following implementation to get better understanding −
from collections import Counter
def solve(nums):
cnt = Counter(nums)
for x in sorted(cnt, key=abs):
if cnt[x] > cnt[2 * x]:
return False
cnt[2 * x] -= cnt[x]
return True
nums = [4,-2,2,-4]
print(solve(nums))Input
[6,0,8,2,1,5]
Output
True