2007. Find Original Array From Doubled Array
Description
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.
Example 1:
Input: changed = [1,3,4,2,6,8] Output: [1,3,4] Explanation: One possible original array could be [1,3,4]: - Twice the value of 1 is 1 * 2 = 2. - Twice the value of 3 is 3 * 2 = 6. - Twice the value of 4 is 4 * 2 = 8. Other original arrays could be [4,3,1] or [3,1,4].
Example 2:
Input: changed = [6,3,0,1] Output: [] Explanation: changed is not a doubled array.
Example 3:
Input: changed = [1] Output: [] Explanation: changed is not a doubled array.
Constraints:
1 <= changed.length <= 105
0 <= changed[i] <= 105
Solutions
Solution: Greedy
- Time complexity: O(nlogn)
- Space complexity: O(n)
JavaScript
js
/**
* @param {number[]} changed
* @return {number[]}
*/
const findOriginalArray = function (changed) {
const changedMap = changed.reduce((map, value) => {
const count = map.get(value) ?? 0;
return map.set(value, count + 1);
}, new Map());
const result = [];
const values = [...changedMap.keys()].sort((a, b) => a - b);
for (const value of values) {
const count = changedMap.get(value);
if (!count) continue;
if (value === 0) {
if (count % 2) return [];
result.push(...Array.from({length: count / 2}).fill(0));
continue;
}
if (changedMap.has(value * 2)) {
const doubledCount = changedMap.get(value * 2);
if (count > doubledCount) return [];
result.push(...new Array(count).fill(value));
changedMap.set(value * 2, doubledCount - count);
continue;
}
return [];
}
return result;
};