Find Original Array From Doubled Array - Problem

Imagine you have an array of numbers, and someone creates a mysterious new array by doubling every element and then shuffling everything together. Your mission is to be a digital detective and reverse this process!

Given an array called changed, determine if it's actually a "doubled array" - meaning it was created by taking some original array, doubling each element, combining them, and shuffling. If it is, return the original array. If it's impossible, return an empty array.

Example: If the original array was [1, 3, 4], the doubled array would contain [1, 3, 4, 2, 6, 8] in some order (each original number plus its double).

The elements in your answer can be in any order - you just need to find what the original array could have been!

Input & Output

example_1.py โ€” Simple Case
$ Input: changed = [1,3,4,2,6,8]
โ€บ Output: [1,3,4]
๐Ÿ’ก Note: The original array could be [1,3,4]. Doubling gives [1,3,4,2,6,8]. After shuffling, we get the input array. Each original element (1,3,4) pairs perfectly with its double (2,6,8).
example_2.py โ€” Impossible Case
$ Input: changed = [6,3,0,1]
โ€บ Output: []
๐Ÿ’ก Note: This cannot be a doubled array. We have 6 but no 12, we have 3 but no 6 available (since 6 would need to pair with 12), we have 1 but no 2. No valid pairing exists.
example_3.py โ€” Empty Array
$ Input: changed = []
โ€บ Output: []
๐Ÿ’ก Note: Empty array is valid - the original array was also empty. Zero elements can be perfectly paired (vacuously true).

Constraints

  • 1 โ‰ค changed.length โ‰ค 105
  • 0 โ‰ค changed[i] โ‰ค 105
  • The array length must be even for a valid doubled array

Visualization

Tap to expand
๐Ÿงฆ The Sock Pairing ChallengeStep 1: The Laundry Basket (Unsorted Array)134268Small socks (1,3,4)Large socks (2,6,8)Step 2: Sort by Size (Sorted Array)123468Now organized!Step 3: Perfect Pairing12Pair!36Pair!48Pair!Original: [1, 3, 4]Each small sock found itsperfect double-sized partner!๐ŸŽฏ Key Insight: Sort First, Then Pair SystematicallyThis prevents confusion and ensures optimal O(n log n) performance!
Understanding the Visualization
1
Dump the Laundry
You have a basket of mixed socks in random order
2
Sort by Size
Arrange socks from smallest to largest for systematic pairing
3
Pair Small with Large
Match each small sock with its double-sized partner
4
Check Completeness
If every sock finds its pair, you've solved the puzzle!
Key Takeaway
๐ŸŽฏ Key Insight: Just like sorting socks makes pairing easier, sorting the array first ensures we process smaller elements before larger ones, preventing conflicts and achieving optimal O(n log n) performance!
Asked in
Google 45
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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