Recover the Original Array - Problem

Imagine Alice had an array of n positive integers. She performed a clever transformation: she picked a positive integer k and created two new arrays by subtracting k from each element (creating the lower array) and adding k to each element (creating the higher array).

Here's the twist: Alice accidentally mixed all the numbers from both arrays together and lost track of the original array! ๐Ÿค”

Your mission: Given an array nums containing 2n integers (where exactly n came from the lower array and n came from the higher array), reconstruct Alice's original array.

Example: If the original array was [5, 10, 15] with k=2, Alice would create:

  • Lower: [3, 8, 13] (subtract 2 from each)
  • Higher: [7, 12, 17] (add 2 to each)
  • Mixed: [3, 7, 8, 12, 13, 17] (shuffled together)

From the mixed array, you need to find the original [5, 10, 15]!

Input & Output

example_1.py โ€” Basic case with k=1
$ Input: [2,10,6,4,8,12]
โ€บ Output: [3,7,11]
๐Ÿ’ก Note: The original array [3,7,11] with k=1 creates lower=[2,6,10] and higher=[4,8,12]. When mixed: [2,10,6,4,8,12]
example_2.py โ€” Larger k value
$ Input: [1,1,3,3]
โ€บ Output: [2,2]
๐Ÿ’ก Note: The original array [2,2] with k=1 creates lower=[1,1] and higher=[3,3]. Mixed together: [1,1,3,3]
example_3.py โ€” Single element case
$ Input: [5,11]
โ€บ Output: [8]
๐Ÿ’ก Note: The original array [8] with k=3 creates lower=[5] and higher=[11]. Mixed: [5,11]

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยณ)

O(nยฒ) possible k values, each requiring O(n) verification time

n
2n
โš  Quadratic Growth
Space Complexity
O(n)

Space for frequency map and result array

n
2n
โšก Linearithmic Space

Constraints

Asked in
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