Problem Description
Alice originally had an array arr of n positive integers. She selected a positive integer k and built two arrays: lower where lower[i] = arr[i] - k and higher where higher[i] = arr[i] + k. The 2n numbers obtained by merging these two arrays (in arbitrary order) are given in nums. The task is to recover any valid original array arr. Note that k must be positive, so the pairing must enforce that the difference between the paired numbers is positive and even.
Key Insights
- Because lower[i] = arr[i] - k and higher[i] = arr[i] + k, each pair of corresponding numbers differs by exactly 2*k.
- In the merged array, the smallest number must come from the lower array.
- For the smallest number low, any candidate x with x > low that makes (x - low) even is a potential partner to determine k.
- Once k is chosen (k = (x - low)/2), every lower value x must have a matching x + 2*k.
- A greedy pairing using a frequency map (or multiset) on the sorted nums can verify candidate k and help recover arr.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting, where n is the number of elements in the original arr. Space Complexity: O(n) for the frequency map and for storing the result.
Solution
The algorithm starts by sorting nums. Since lower elements are always smaller than their corresponding higher elements (by exactly 2k), the smallest number in nums must be part of the lower array. For every candidate number in nums (other than the smallest), if the difference with the smallest number is even and positive, we compute a candidate k as (candidate - smallest)/2. We then try to pair every remaining number. Using a frequency map, we repeatedly take the smallest available number as a potential lower element and check if its corresponding higher element (i.e. lower + 2k) exists in the map. If all numbers can be successfully paired, we compute the original number as lower + k and add it to the answer. If pairing fails at any point, we move to the next candidate for k. This greedy approach assures correctness because the problem guarantees at least one valid answer exists.