- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if elements of an array can be arranged satisfying the given condition 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
- if freq[item] is 0, then
- return True
Example
Let us see the following implementation to get better understanding −
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
- Related Articles
- Check if elements of array can be made equal by multiplying given prime numbers in Python
- C++ Program to find an array satisfying an condition
- Check if an array contains all elements of a given range in Python
- Check if given string can be formed by concatenating string elements of list in Python
- Check if the array can be sorted using swaps between given indices only in Python
- Check if the given array can be reduced to zeros with the given operation performed given number of times in Python
- Check if array can be sorted with one swap in Python
- Check if array elements are consecutive in Python
- Check if subarray with given product exists in an array in Python
- Check if given string can be split into four distinct strings in Python
- Check if the elements of the array can be rearranged to form a sequence of numbers or not in JavaScript
- Check if an array can be divided into pairs whose sum is divisible by k in Python
- Check if an array of 1s and 2s can be divided into 2 parts with equal sum in Python
- Check if all array elements are distinct in Python
- Check if a two-character string can be made using given words in Python

Advertisements