Skip to main content
Back to problems
#2122
Hard Algorithms

Recover the original array

Array Hash Table Two Pointers Sorting Enumeration
41.3% acceptance
Feb 25, 2026
392
33
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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn recover_array(nums: Vec<i32>) -> Vec<i32> {
    use std::collections::BTreeMap;
    let mut nums = nums;
    nums.sort();
    let n = nums.len();

    // nums[0] is minimum; it must be in lower[], paired with nums[0] + 2k
    for i in 1..n {
      let diff = nums[i] - nums[0];
      if diff == 0 || diff % 2 != 0 {
        continue;
      }
      let k = diff / 2;

      // Build frequency map and try to pair greedily
      let mut cnt: BTreeMap<i32, usize> = BTreeMap::new();
      for &x in &nums {
        *cnt.entry(x).or_default() += 1;
      }

      let mut arr = Vec::new();
      let mut success = true;

      for &x in &nums {
        if *cnt.get(&x).unwrap_or(&0) == 0 {
          continue;
        }
        let upper = x + 2 * k;
        if *cnt.get(&upper).unwrap_or(&0) == 0 {
          success = false;
          break;
        }
        *cnt.get_mut(&x).unwrap() -= 1;
        if cnt[&x] == 0 {
          cnt.remove(&x);
        }
        *cnt.get_mut(&upper).unwrap() -= 1;
        if cnt[&upper] == 0 {
          cnt.remove(&upper);
        }
        arr.push(x + k);
      }

      if success && arr.len() == n / 2 {
        return arr;
      }
    }
    vec![]
  }
}