Find Original Array From Doubled Array — LeetCode 2007 Python Solution
- Problem
- #2007
- Pattern
- Greedy
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- Input
- changed = [1,3,4,2,6,8]
- Output
- [1,3,4]
- Explanation
- One possible original array could be [1,3,4]:
Python solution
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n), where n is the length of the array `changed` auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2007. Find Original Array From Doubled Array is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2007. Find Original Array From Doubled Array?
- LeetCode 2007. Find Original Array From Doubled Array is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2007. Find Original Array From Doubled Array?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2007. Find Original Array From Doubled Array?
- The Python solution on this page uses O(n), where n is the length of the array `changed` auxiliary space.
- What topics does LeetCode 2007. Find Original Array From Doubled Array cover?
- LeetCode 2007. Find Original Array From Doubled Array is tagged Greedy, Array, Hash Table and Sorting on LeetCode.