Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find array of doubled pairs using Python
Given an array of integers with even length, we need to check if it's possible to reorder the array such that nums[2*i + 1] = 2*nums[2*i] for every index 0 <= i < len(nums)/2. This means we need to pair each element with its double value.
So, if the input is like nums = [4,-2,2,-4], then the output will be True because we can arrange it as [-2, -4, 2, 4] where -4 = 2*(-2) and 4 = 2*2.
Algorithm Steps
To solve this problem, we will follow these steps ?
Create a frequency counter of all elements in the array
Sort elements by their absolute values to handle negative numbers properly
For each element, check if we have enough doubles to pair with
If any element cannot find sufficient pairs, return
FalseOtherwise, return
True
Implementation
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
# Test case 1
nums1 = [4, -2, 2, -4]
print("Array:", nums1)
print("Can form doubled pairs:", solve(nums1))
# Test case 2
nums2 = [2, 1, 2, 6]
print("Array:", nums2)
print("Can form doubled pairs:", solve(nums2))
The output of the above code is ?
Array: [4, -2, 2, -4] Can form doubled pairs: True Array: [2, 1, 2, 6] Can form doubled pairs: False
How It Works
The algorithm works by using a greedy approach:
Frequency Counting: We count occurrences of each number using
CounterSorting by Absolute Value: This ensures we process smaller absolute values first, which is crucial for pairing
Pairing Check: For each number
x, we need at leastcnt[x]occurrences of2*xto form valid pairsUpdate Counter: After pairing, we reduce the count of doubles by the number of pairs formed
Edge Cases
Let's test with an edge case involving zero ?
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
# Edge case with zero
nums3 = [0, 0]
print("Array with zeros:", nums3)
print("Can form doubled pairs:", solve(nums3))
The output shows ?
Array with zeros: [0, 0] Can form doubled pairs: True
Conclusion
This greedy algorithm efficiently determines if an array can be reordered into doubled pairs by using frequency counting and sorting by absolute values. The time complexity is O(n log n) due to sorting, where n is the array length.
