Recover the Original Array - Problem

Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner:

  • lower[i] = arr[i] - k, for every index i where 0 <= i < n
  • higher[i] = arr[i] + k, for every index i where 0 <= i < n

Unfortunately, Alice lost all three arrays. However, she remembers the integers that were present in the arrays lower and higher, but not the array each integer belonged to. Help Alice and recover the original array.

Given an array nums consisting of 2n integers, where exactly n of the integers were present in lower and the remaining in higher, return the original array arr. In case the answer is not unique, return any valid array.

Note: The test cases are generated such that there exists at least one valid array arr.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,10,6,4,8,12]
Output: [3,7,5]
💡 Note: If k=2, then lower=[1,5,3] and higher=[5,9,7]. The combined array is [1,5,3,5,9,7]. When sorted: [1,3,5,5,7,9]. Pairing (1,5)→3, (3,7)→5, (5,9)→7 gives original=[3,5,7]. But the actual pairing that works is different - we need to find the right k first.
Example 2 — Simple Pattern
$ Input: nums = [1,1,3,3]
Output: [2,2]
💡 Note: With k=1: lower=[1,1] and higher=[3,3], so original=[2,2]. Each original element 2 creates pair (2-1, 2+1) = (1,3).
Example 3 — Larger Difference
$ Input: nums = [5,435]
Output: [220]
💡 Note: With k=215: lower=[5] and higher=[435], so original=[220]. Single element case where 220-215=5 and 220+215=435.

Constraints

  • 2 ≤ nums.length ≤ 1000
  • nums.length is even
  • -1000 ≤ nums[i] ≤ 1000
  • The test cases are generated such that there exists at least one valid array arr.

Visualization

Tap to expand
INPUTALGORITHMRESULTMixed Array[2,10,6,4,8,12]21064812Some from lower: arr[i] - kSome from higher: arr[i] + k1Sort array2Find k using smallest3Pair elements greedily4Build original arrayk = 2Pairs: (2,6)→4, (4,8)→6, (10,12)→8Original Array468[4,6,8]Each element createsa (lower, higher) pairKey Insight:The smallest element must be from the lower array, giving us the key to find kTutorialsPoint - Recover the Original Array | Optimal Greedy Approach
Asked in
Google 15 Facebook 12 Amazon 8
28.7K Views
Medium Frequency
~35 min Avg. Time
892 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