Find Original Array From Doubled Array LeetCode solution in Python
1class Solution:2def findOriginalArray(self, changed: List[int]) -> List[int]:3counter = collections.Counter(changed)4res = []5for k in counter.keys():67if k == 0:8# handle zero as special case9if counter[k] % 2 > 0:10return []11res += [0] * (counter[k] // 2)1213elif counter[k] > 0:14x = k1516# walk down the chain17while x % 2 == 0 and x // 2 in counter:18x = x // 21920# walk up and process all numbers within the chain. mark the counts as 021while x in counter:22if counter[x] > 0:23res += [x] * counter[x]24if counter[x + x] < counter[x]:25return []26counter[x + x] -= counter[x]27counter[x] = 028x += x29return res