
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find array of doubled pairs using Python
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
- Related Articles
- Array of Doubled Pairs in C++
- Program to find number of good leaf nodes pairs using Python
- Program to find array by swapping consecutive index pairs in Python
- Program to find number of good pairs in Python
- Program to check if array pairs are divisible by k or not using Python
- Python Program to find out the number of matches in an array containing pairs of (base, number)
- Program to restore the array from adjacent pairs in Python
- Program to count nice pairs in an array in Python
- Program to find the winner of an array game using Python
- Program to find sign of the product of an array using Python
- Program to find max number of K-sum pairs in Python
- Program to Find K-Largest Sum Pairs in Python
- Program to find XOR sum of all pairs bitwise AND in Python
- Find the Number of Prime Pairs in an Array using C++
- Find the Number of Unique Pairs in an Array using C++

Advertisements