Check if elements of an array can be arranged satisfying the given condition in Python

Sometimes we need to check if array elements can be rearranged to satisfy a specific pairing condition. In this problem, we want to arrange elements such that for every even index i, the element at odd index 2*i + 1 equals twice the element at even index 2*i.

The condition is: nums[2*i + 1] = 2 * nums[2*i] for all valid indices i.

Understanding the Problem

For the array [8, -4, 4, -8], we can rearrange it as [-4, -8, 4, 8]:

  • For i = 0: nums[1] = -8, which equals 2 * nums[0] = 2 * (-4) = -8 ?
  • For i = 1: nums[3] = 8, which equals 2 * nums[2] = 2 * 4 = 8 ?

Algorithm Steps

To solve this efficiently, we follow these steps:

  • Create a frequency map of all elements
  • Sort elements by their absolute values to handle negative numbers correctly
  • For each element, try to pair it with its double
  • If pairing fails for any element, return False
  • If all elements can be paired, return True

Implementation

from collections import defaultdict

def solve(nums):
    freq = defaultdict(int)
    
    # Count frequency of each element
    for item in nums:
        freq[item] += 1
    
    # Sort by absolute values to handle negatives properly
    for item in sorted(nums, key=abs):
        if freq[item] == 0:
            continue
        if freq[2 * item] == 0:
            return False
        
        # Pair current item with its double
        freq[item] -= 1
        freq[2 * item] -= 1
    
    return True

# Test with example
nums = [8, -4, 4, -8]
print(solve(nums))
True

How It Works

The algorithm uses a greedy approach by sorting elements by absolute value. This ensures smaller elements are paired first, preventing larger elements from "stealing" the doubles of smaller ones. For negative numbers, this maintains the correct pairing relationships.

Additional Example

# Test with an impossible case
nums2 = [1, 2, 4, 16, 8, 4]
print(f"Array {nums2}: {solve(nums2)}")

# Test with another valid case
nums3 = [2, 1, 2, 6, 4, 2]
print(f"Array {nums3}: {solve(nums3)}")
Array [1, 2, 4, 16, 8, 4]: False
Array [2, 1, 2, 6, 4, 2]: False

Time Complexity

The time complexity is O(n log n) due to sorting, where n is the length of the array. The space complexity is O(n) for the frequency map.

Conclusion

This greedy approach efficiently determines if array elements can be rearranged to satisfy the doubling condition. Sorting by absolute value ensures correct pairing for both positive and negative numbers.

Updated on: 2026-03-25T14:58:48+05:30

305 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements