[LeetCode] Recover the Original Array

2122. Recover the Original Array

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:

  1. lower[i] = arr[i] - k, for every index i where 0 <= i < n
  2. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
int getK(vector<int>& A, int i, int j) {
int ak = A[i] - A[0], zk = A.back() - A[j];
if(ak == zk and !(ak & 1))
return ak / 2;
return INT_MIN;
}
vector<int> kCand(vector<int>& A) {
int sum = A[0] + A.back(); //A - k + Z + k
int n = A.size();
vector<pair<int,int>> cand;

for(int i = 1; i < n; i++) { //find A + k + Z - k combinations
n = lower_bound(begin(A) + i, begin(A) + n, sum - A[i]) - begin(A);

if(A[n] + A[i] == sum)
cand.push_back({i,n});
}
unordered_set<int> res;
for(auto [i, j] : cand) {
int k1 = getK(A,i,j), k2 = getK(A,j,i);
if(k1 != INT_MIN) res.insert(k1);
if(k2 != INT_MIN) res.insert(k2);
}

return vector<int>(begin(res),end(res));
}
bool helper(vector<int>& A, unordered_map<int,int>& mp, int& k, vector<int>& res, int p, int i) {
if(p == A.size()) return true;
if(mp[A[p]] == 0) return helper(A,mp,k,res,p+1,i);
if(mp[A[p] + 2*k] == 0 or i == res.size()) return false;
mp[A[p] + 2*k]--;
mp[A[p]]--;
res[i] = A[p] + k;

if(helper(A,mp,k,res,p+1,i+1)) return true;

mp[A[p] + 2*k]++;
mp[A[p]]++;

return false;
}
public:
vector<int> recoverArray(vector<int>& A) {
sort(begin(A), end(A));
if(A.size() == 2) return {(A[0] + A[1]) / 2};

auto kc = kCand(A);
int n = A.size();
unordered_map<int, int> mp;
for(auto& a : A) mp[a]++;

vector<int> res(n/2);
for(auto& k : kc)
if(helper(A,mp,k,res,0,0)) {
return res;
}
return {};

}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/22/PS/LeetCode/recover-the-original-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.