Problem Description
Given an integer array of even length arr, determine if it is possible to reorder the array such that for every index i, arr[2i + 1] equals 2 * arr[2i]. In other words, can we form pairs [x, 2*x] using all the elements of the array?
Key Insights
- Sort the array based on the absolute value of the elements to handle negative numbers correctly.
- Use a hash table (or frequency counter) to track the occurrence of each element.
- For each number in the sorted list, if the number is still available in the frequency map, try to pair it with its double.
- Decrement the appropriate counts and validate that it is possible to find sufficient doubles for all numbers.
- Special case: when dealing with zeros, pairing works within the same value.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting. Space Complexity: O(n) for storing the frequency map.
Solution
The solution starts by counting the frequency of each element in the array. Sorting the array by absolute value ensures that when we process an element, any potential pair (i.e., its double) comes later in the sequence. For each number, if there are available occurrences, we try to match it with its double. If there are not enough doubles available, the answer is false. If all elements can be paired appropriately by decrementing their counts in the frequency map, the function returns true.