
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 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
- 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
Advertisements