Problem Description
Given an array "changed" that is claimed to be created by taking an original array, appending twice each of its elements, and shuffling the resulting array, determine the original array. If "changed" is not a valid doubled array, return an empty array.
Key Insights
- The length of "changed" must be even since it consists of the original array and its doubled counterpart.
- Sorting the array helps to process elements in increasing order so that if an element x exists, then its pair 2*x can be looked up.
- Use frequency counting (hash table) to match each x with its doubled value 2*x.
- Special care is needed for zeros because 0 doubled is still 0.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting of the array. Space Complexity: O(n) for the hash table storing frequency counts and the result array.
Solution
We first check if the "changed" array has an even number of elements, returning an empty array if not. Then, we sort the array and build a frequency dictionary. For each number in sorted order, if it appears in the dictionary, its corresponding doubled value must also appear sufficiently. If not, the array is not a valid doubled array. Otherwise, we add the original elements to our result and decrement the frequency for the doubled values accordingly. Special care must be taken for the case when the number is 0 since its pair is also 0.