#2007
Find Original Array From Doubled Array
MediumArrayHash TableGreedySortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution uses a HashMap to count occurrences of each number, allowing us to efficiently check and remove elements and their doubles in linear time.
⚙️
Algorithm
6 steps- 1Step 1: Create a frequency map (HashMap) to count occurrences of each number in the changed array.
- 2Step 2: Sort the keys of the frequency map to handle smaller numbers first.
- 3Step 3: For each number, check if its double exists in the map with a sufficient count.
- 4Step 4: If it does, add the number to the original array and decrease the counts accordingly.
- 5Step 5: If any number cannot be paired with its double, return an empty array.
- 6Step 6: Return the original array if all checks pass.
solution.py13 lines
1# Full working Python code
2
3def findOriginalArray(changed):
4 if len(changed) % 2 != 0:
5 return []
6 count = Counter(changed)
7 original = []
8 for num in sorted(count.keys()):
9 if count[num] > count[num * 2]:
10 return []
11 original.extend([num] * (count[num]))
12 count[num * 2] -= count[num]
13 return originalℹ
Complexity note: The time complexity is O(n log n) due to sorting the array, and the space complexity is O(n) for storing the frequency map.
- 1If the length of the changed array is odd, it cannot be a doubled array.
- 2The smallest element in the changed array is guaranteed to be part of the original array.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.