VOOZH about

URL: https://www.geeksforgeeks.org/dsa/construct-array-pair-sum-array/

⇱ Construct an array from its pair-sum array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Construct an array from its pair-sum array

Last Updated : 22 Jul, 2025

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:

  • First: res[0] + res[1]
  • Then: res[0] + res[2], res[0] + res[3], ..., res[0] + res[n-1]
  • Then: res[1] + res[2], res[1] + res[3], ..., and so on,
  • Until all unique pairs (i, j) such that i < j are covered.

Notes:

  • The size of the input array arr[] is always n × (n - 1) / 2, which is the number of unique pairs in an array of size n.
  • The task is to reconstruct the original array res[] from arr[].
  • It is not guaranteed that a valid res[] exists for every input arr[].
  • There can be multiple valid original arrays that result in the same pair-sum array.

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.

[Approach] Pair-Sum Decomposition

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:

👁 23

Output
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.

Comment
Article Tags:
Article Tags: