![]() |
VOOZH | about |
Given a pair-sum array arr[], where each element represents the sum of a unique pair of elements from an unknown original array res[].
The pairs are considered in a specific order:
Notes:
Examples
Input: arr[] = [4, 5, 3]
Output: [3, 1, 2]
Explanation: For [3, 1, 2], pairwise sums are (3 + 1), (3 + 2) and (1 + 2)Input: arr[] = [3]
Output: [1, 2]
Explanation: There may be multiple valid original arrays that produce the same pair-sum array, such as[1, 2]and[2, 1]. Both are considered correct since they yield the same set of pairwise sums.
The approach begins by determining the size n of the original array using the formula for the number of unique pairs: n*(n-1)/2 = length of arr
Solving this gives the size of the original array.Once n is known, we focus on the first three elements of the pair-sum array. These represent the sums:
- arr[0] = res[0] + res[1]
- arr[1] = res[0] + res[2]
- arr[2] = res[1] + res[2]
By adding the first two and subtracting the third, we can isolate res[0]: res[0] = (arr[0] + arr[1] - arr[2]) / 2.
After finding res[0], the rest of the values in res can be easily calculated. Since the next n - 1 values in arr represent res[0] + res[1], res[0] + res[2], ..., res[0] + res[n-1], we can subtract res[0] from each to find res[1] through res[n-1].
So, for each i from 1 to n - 1: res[i] = arr[i-1] - res[0].
Illustration:
3 1 2
Time Complexity: O(n), where n is the size of the original array, since we compute each element of res[] in a single pass.
Auxiliary Space: O(n), for storing the output array res[], no extra space is used beyond that.