Check Array Elements Arrangement in Python



Suppose we have an array called nums. We have to check whether it is possible to rearrange the elements of nums such that it follows the condition −

So, if the input is like nums = [8, -4, 4, -8], then the output will be True as if we arrange the array like [-4, -8, 4, 8] for i = 0, nums[2*0 + 1] = 2 * (-4) = -8 for i = 1, nums[2*1 + 1] = 2 * 4 = 8

To solve this, we will follow these steps −

  • freq := a map containing elements of nums and their frequencies
  • for each item in nums sorted in their absolute values, do
    • if freq[item] is 0, then
      • go for next iteration
    • if freq[2 * item] is 0, then
      • return False
    • freq[item] := freq[item] - 1
    • freq[2 * item] := freq[2 * item] - 1
  • return True

Example

Let us see the following implementation to get better understanding −

 Live Demo

from collections import defaultdict
def solve(nums):
   freq = defaultdict(int)
   for item in nums:
      freq[item] += 1
   for item in sorted(nums, key = abs):
      if freq[item] == 0:
         continue
      if freq[2 * item] == 0:
         return False
      freq[item] -= 1
      freq[2 * item] -= 1
   return True
nums = [8, -4, 4, -8]
print(solve(nums))

Input

[8, -4, 4, -8]

Output

True
Updated on: 2021-01-18T12:20:02+05:30

225 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements