Find Original Array From Doubled Array Problem
Description
LeetCode Problem 2007.
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 <= 10^50 <= changed[i] <= 10^5
Solution
Approach: Sort and Match Smallest First
If the array is a doubled array, its smallest remaining value must belong to the original array, because it cannot be the double of anything smaller. So process the values in ascending order:
- skip a value whose count is already zero (it was used up as somebody's double);
- otherwise it is an original element
x: use one copy, and take one copy of2xas its double. If there is no copy of2xleft, the array is not a doubled array and the answer is empty; - add
xto the original array.
The value 0 works too: its double is itself, so zeros must come in pairs, which the same count check enforces. An odd length can never succeed.
Because the loop goes through the sorted array, the answer comes out in ascending order.
Complexity: O(n log n) time for the sort and O(M) space for the counts, where M is the largest value.
from collections import Counter
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
changed.sort()
cnt = Counter(changed)
ans = []
for x in changed:
if cnt[x] == 0:
continue
cnt[x] -= 1
if cnt[x << 1] <= 0:
return []
cnt[x << 1] -= 1
ans.append(x)
return ans