Problem
An integer array original
is transformed into a doubled array changed
by appending twice the value of every element in original
, and then randomly shuffling the resulting array.
Given an array changed
, return original
if changed
is a doubled array. If changed
is not a doubled array, return an empty array. The elements in original
may be returned in any order.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
This problem is similar to Array of Doubled Pairs.
Method 1 – Sorting and Frequency Map
Intuition
The main idea is to pair each number with its double. By sorting the array, we can always try to pair the smallest available number first, which helps handle negative numbers and zeros correctly. We use a frequency map to track how many times each number appears and greedily match each number with its double.
Approach
- Sort the array to process numbers in order, handling negatives and zeros properly.
- Use a frequency map to count occurrences of each number.
- For each number in the sorted array:
- If its frequency is zero, skip it.
- If its double’s frequency is zero, return an empty array.
- Otherwise, decrement the frequency of both the number and its double and add the number to the answer.
- If all numbers are paired successfully, return the answer array.
Dry Run
Let’s dry run the algorithm for changed = [1,3,4,2,6,8]
:
- Sort:
[1,2,3,4,6,8]
- Frequency:
{1:1, 2:1, 3:1, 4:1, 6:1, 8:1}
- Process 1:
freq[1]=1, freq[2]=1 → add 1, freq[1]=0, freq[2]=0
- Process 2:
freq[2]=0 (skip)
- Process 3:
freq[3]=1, freq[6]=1 → add 3, freq[3]=0, freq[6]=0
- Process 4: f
req[4]=1, freq[8]=1 → add 4, freq[4]=0, freq[8]=0
- Process 5: f
req[6]=0 (skip)
- Process 6:
freq[8]=0 (skip)
- Result:
[1,3,4]
Complexity
- ⏰ Time complexity:
O(n log n)
, wheren
is the length ofchanged
, due to sorting and linear scan. - 🧺 Space complexity:
O(n)
, for the frequency map and answer array.
Code
|
|
|
|
|
|