Find Original Array From Doubled Array - 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. If changed is not a doubled array, return an empty array.

The elements in original may be returned in any order.

Input & Output

Example 1 — Basic Case
$ Input: changed = [1,3,4,2,6,8]
Output: [1,3,4]
💡 Note: Original array [1,3,4] becomes [1,3,4,2,6,8] after doubling [2,6,8] and shuffling. We can recover [1,3,4] by pairing: 1↔2, 3↔6, 4↔8.
Example 2 — Impossible Case
$ Input: changed = [6,3,0,1]
Output: []
💡 Note: Cannot form valid pairs. We have 6 but no 12, and 3 but no 6 available after pairing other elements.
Example 3 — With Zeros
$ Input: changed = [0,0,2,1]
Output: [0,1]
💡 Note: Zeros pair with themselves: 0↔0, and 1↔2. Original array could be [0,1].

Constraints

  • 1 ≤ changed.length ≤ 105
  • 0 ≤ changed[i] ≤ 105

Visualization

Tap to expand
Find Original Array From Doubled Array INPUT changed array: 1 3 4 2 6 8 [0] [1] [2] [3] [4] [5] After Sorting: 1 2 3 4 6 8 Frequency Map: 1:1, 2:1, 3:1 4:1, 6:1, 8:1 ALGORITHM STEPS 1 Sort + Count Sort array, build freq map 2 Process Each For each num, check 2*num 3 Pair Matching Match num with its double 4 Build Result Add original to result Pairing Process: 1 --> 2 OK 3 --> 6 OK 4 --> 8 OK Original Double FINAL RESULT Original Array Found: 1 3 4 Output: [1, 3, 4] Verification: 1 * 2 = 2 OK 3 * 2 = 6 OK 4 * 2 = 8 OK [1,3,4] + [2,6,8] = changed Valid Doubled Array! Key Insight: By sorting the array first, we ensure we always process smaller numbers before their doubles. Using a frequency map allows O(1) lookup to check if double exists. Time: O(n log n), Space: O(n). For each original number x, we must find exactly one occurrence of 2x in the remaining elements. TutorialsPoint - Find Original Array From Doubled Array | Optimal Solution
Asked in
Facebook 15 Google 12 Microsoft 8
58.0K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen