Open In App

Construct an array from its pair-sum array

Last Updated : 28 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given a pair-sum array construct the original array. A pair-sum array for an array is the array that contains sum of all pairs in ordered form, i.e., pair[0] is sum of arr[0] and arr[1], pair[1] is sum of arr[0] and arr[2] and so on. Note that if the size of input array is n, then the size of pair array would be n * (n -1) /2. We may assume that the input array is a valid pair sum array and has appropriate size.

Examples

Input : pair[] = {4, 5, 3}
Output : arr[] = {3, 1, 2}
Explanation : For {1, 3, 2}, pairwise sums are (3 + 1), ( 3 + 2) and (1 + 2)

Input : pair[] = {3}
Output : arr[] = {1, 2}
Explanation : There is only one pair

How to compute size of the input array?

Let the output array be of size n and input pair array of size n(n-1)/2. Let the size of the pair array be k

k = n*(n-1)/2

Solving the above equation for n, we get

n = (1 + sqrt(1 + 8 * k)) / 2;

How to find Individual Elements?

If we compute arr[0], we can easily compute rest of the values. arr[1] = pair[0] – arr[0], arr[2] = pair[1] – arr[0] and so on. Let us see the below pattern

pair[0] = arr[0] + arr[1]
pair[1] = arr[0] + arr[2]
…………………………………..
pair[n-2] = arr[0] + arr[n-1]
pair[n-1] = arr[1] + arr[2]

Can we find arr[0] using only pair values? If we take a closer look, we can notice that arr[0] can be computed using the following equation.
arr[0] = 1/2(pair[0] + pair[1] – pair[n-1])

Following is the implementation of the above idea. 

C++
#include <bits/stdc++.h>
using namespace std;

// Constructs arr[] from its pair sum array pair[]
vector<int> constructArr(vector<int>& pair) {
    
    // Size of the result array
    int n = (1 + sqrt(1 + 8 * pair.size())) / 2;
    
    // Find the result array
    vector<int> arr(n);
    arr[0] = (pair[0] + pair[1] - pair[n - 1]) / 2;
    for (int i = 1; i < n; i++)
        arr[i] = pair[i - 1] - arr[0];
        
    return arr;
}

// Driver program to test the function
int main() {
    vector<int> pair = {15, 13, 11, 10, 12, 10, 9, 8, 7, 5};
    vector<int> arr = constructArr(pair);
    for (int x : arr)
        cout << x << " ";
    return 0;
}
Java Python C# JavaScript


Time complexity O(n)
Auxiliary Space: O(1)
 



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg