The Wayback Machine - http://web.archive.org/web/20241007083808/https://www.geeksforgeeks.org/construct-array-pair-sum-array/
Open In App

Construct an array from its pair-sum array

Last Updated : 10 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a pair-sum array and size of the original array (n), construct the original array.
A pair-sum array for an array is the array that contains sum of all pairs in ordered form. For example pair-sum array for arr[] = {6, 8, 3, 4} is {14, 9, 10, 11, 12, 7}.
In general, pair-sum array for arr[0..n-1] is {arr[0]+arr[1], arr[0]+arr[2], ……., arr[1]+arr[2], arr[1]+arr[3], ……., arr[2]+arr[3], arr[2]+arr[4], …., arr[n-2]+arr[n-1}.
“Given a pair-sum array, construct the original array.”
We strongly recommend to minimize your browser and try this yourself.
Let the given array be “pair[]” and let there be n elements in original array. If we take a look at few examples, we can observe that arr[0] is half of pair[0] + pair[1] – pair[n-1]. Note that the value of pair[0] + pair[1] – pair[n-1] is (arr[0] + arr[1]) + (arr[0] + arr[2]) – (arr[1] + arr[2]). 
Once we have evaluated arr[0], we can evaluate other elements by subtracting arr[0]. For example arr[1] can be evaluated by subtracting arr[0] from pair[0], arr[2] can be evaluated by subtracting arr[0] from pair[1].
Following is the implementation of the above idea.
 

C++




#include <bits/stdc++.h>
using namespace std;
 
// Fills element in arr[] from its pair sum array pair[].
// n is size of arr[]
void constructArr(int arr[], int pair[], int 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];
}
 
// Driver program to test above function
int main()
{
    int pair[] = {15, 13, 11, 10, 12, 10, 9, 8, 7, 5};
    int n = 5;
    int arr[n];
    constructArr(arr, pair, n);
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    return 0;
}


Java




import java.io.*;
 
class PairSum {
     
    // Fills element in arr[] from its pair sum array pair[].
    // n is size of arr[]
    static void constructArr(int arr[], int pair[], int 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];
    }
     
    // Driver program to test above function
    public static void main(String[] args)
    {
        int pair[] = {15, 13, 11, 10, 12, 10, 9, 8, 7, 5};
        int n = 5;
        int[] arr = new int[n];
        constructArr(arr, pair, n);
        for (int i = 0; i < n; i++)
            System.out.print(arr[i]+" ");       
    }
}
/* This code is contributed by Devesh Agrawal */


Python3




# Fills element in arr[] from its
# pair sum array pair[].
# n is size of arr[]
 
def constructArr(arr,pair,n):
    arr [0] = (pair[0]+pair[1]-pair[n-1])//2
    for i in range(1,n):
        arr[i] = pair[i-1]-arr[0]
 
# Driver code
if __name__=='__main__':
    pair = [15, 13, 11, 10, 12, 10, 9, 8, 7, 5]
    n =5
    arr = [0]*n
    constructArr(arr,pair,n)
    for i in range(n):
        print(arr[i],end =" ")
 
# This code is contributed by
# Shrikant13


C#




// C# program to construct an
// array from its pair-sum array
using System;
 
class PairSum
{
    // Fills element in arr[] from its
    // pair sum array pair[].
    // n is size of arr[]
    static void constructArr(int []arr, int []pair,
                                             int 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];
    }
     
    // Driver program to test above function
    public static void Main()
    {
        int []pair = {15, 13, 11, 10, 12,
                         10, 9, 8, 7, 5};
        int n = 5;
        int []arr = new int[n];
        constructArr(arr, pair, n);
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");    
    }
}
 
// This code is contributed by nitin mittal


PHP




<?php
// Fills element in arr[] from 
// its pair sum array pair[].
// n is size of arr[]
function constructArr($pair)
{
    $arr = array();
    $n = 5;
    $arr[0] = intval(($pair[0] + $pair[1] -
                      $pair[$n - 1]) / 2);
    for ($i = 1; $i < $n; $i++)
        $arr[$i] = $pair[$i - 1] - $arr[0];
         
    for ($i = 0; $i < $n; $i++)
        echo $arr[$i] . " ";
}
 
// Driver Code
$pair = array(15, 13, 11, 10,
              12, 10, 9, 8, 7, 5);
constructArr($pair);
 
// This code is contributed by Sam007
?>


Javascript




<script>
 
// Fills element in arr[] from
// its pair sum array pair[].
// n is size of arr[]
function constructArr(arr, pair, n)
{
    arr[0] = Math.floor((pair[0]+pair[1]-pair[n-1]) / 2);
    for (let i=1; i<n; i++)
        arr[i] = pair[i-1]-arr[0];
}
 
// Driver program to test above function
 
    let pair = [15, 13, 11, 10, 12, 10, 9, 8, 7, 5];
    let n = 5;
    let arr = new Array(n);
    constructArr(arr, pair, n);
    for (let i = 0; i < n; i++)
        document.write(arr[i] + " ");
 
 
// This code is contributed by Surbhi Tyagi.
 
</script>


Output:  

 8 7 5 3 2 

Time complexity of constructArr() is O(n) where n is number of elements in arr[].

Auxiliary Space: O(1)

 



Previous Article
Next Article

Similar Reads

Construct an array from its pair-product
Given a pair-product array pair[], the task is to find the original array. A pair-product array for an array arr[] is the array that contains product of all the pairs in ordered form i.e. {(arr[0] * arr[1]), (arr[0] * arr[2]), ..., (arr[1] * arr[2]), (arr[1] * arr[3]), ..., (arr[n - 2] * arr[n - 1])}.Examples: Input: pair[] = {2, 3, 6} Output: 1 2
5 min read
Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, we need to write a program to construct the binary tree using these two Preorder traversals.A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a general binary tree using these two traver
12 min read
Number of indices pair such that element pair sum from first Array is greater than second Array
Given two integer arrays A[] and B[] of equal sizes, the task is to find the number of pairs of indices {i, j} in the arrays such that A[i] + A[j] > B[i] + B[j] and i < j.Examples: Input: A[] = {4, 8, 2, 6, 2}, B[] = {4, 5, 4, 1, 3} Output: 7 Explanation: There are a total of 7 pairs of indices {i, j} in the array following the condition. The
15+ min read
Construct an array of first N natural numbers such that every adjacent pair is coprime
Given a positive integer N, the task is to construct an array consisting of first N natural numbers such that each pair of adjacent elements in the array is a co-prime. If multiple solutions exist, then print any one of them. Examples: Input: N = 4 Output: 4 1 3 2 Explanation: All possible adjacent pairs of the array are { (4, 1), (1, 3), (3, 2) }
4 min read
Construct a sorted Array such that setbit in bitwise XOR of any pair is even
Given an integer N(1 ≤ N ≤ 500), Construct an integer arr[] of length N, such that it should follow all the given conditions below: Each element of arr[] should be distinct.Binary representation of (arr[i]^arr[j]) should contain even number of set bits for all ( 1≤i≤N ) and ( i≠j ).All the elements in arr[] should be in sorted order.Ai > 0 for a
7 min read
Find the index having sum of elements on its left equal to reverse of the sum of elements on its right
Given an array, arr[] size N, the task is to find the smallest index of the array such that the sum of all the array elements on the left side of the index is equal to the reverse of the digits of the sum of all the array elements on the right side of that index. If no such index is found then print -1. Examples: Input: arr[] = { 5, 7, 3, 6, 4, 9,
15+ min read
Pair the integers of Array so that each pair sum is consecutive and distinct
Given an array arr[]of size N. We have to pair the integers such that each integer should be in exactly one pair and each sum of pairs is consecutive and distinct. Formally, sum(arri + arrj) + 1 = sum(arri1 + arrj1). Print the pairs of integers satisfying all the conditions. If it is not possible to find the pairs return -1. Examples: Input: N = 6,
7 min read
Construct Array with elements in given range and distinct GCD of each element with its index
Given 3 integers N, L and R. The task is to construct an array A[] of N integers, such that : Each element of the array is in the range [L, R].GCD(i, A[i]) are distinct for all elements. Examples : Input : N = 5, L = 1, R = 5Output : {1, 2, 3, 4, 5}Explanation : It can be seen that each element is in the range [1, 5]. Also, for i = 1, GCD(1, 1)=1,
7 min read
Construct a graph which does not contain any pair of adjacent nodes with same value
Given an array arr[] consisting of N characters, the task is to generate a graph of N nodes and (N - 1) Edges such that each node i is associated with character arr[i] and no two adjacent nodes have the same value. If it is possible to make such a graph, then print "Possible" with the pairs of edges. Otherwise, print "Not Possible". Examples: Input
10 min read
Construct an N-ary Tree having no pair of adjacent nodes with same weight from given weights
Given an array weights[] consisting of N positive integer, where weights[i] denotes the weight of ith node, the task is to construct an N-ary tree such that no two directly connected nodes have same weight. If it is possible to make such a tree, then print "Yes" along with their edges. Otherwise, print "No". Examples: Input: weights[] = {1 2 1 2 5}
10 min read
Pair formation such that maximum pair sum is minimized
Given an array of size 2 * N integers. Divide the array into N pairs, such that the maximum pair sum is minimized. In other words, the optimal division of array into N pairs should result into a maximum pair sum which is minimum of other maximum pair sum of all possibilities. Examples: Input : N = 2 , arr[] = { 5, 8, 3, 9 } Output : (3, 9) (5, 8) E
5 min read
Construct sum-array with sum of elements in given range
You are given an array of n-elements and an odd-integer m. You have to construct a new sum_array from given array such that sum_array[i] = ?arr[j] for (i-(m/2)) < j (i+(m/2)). note : for 0 > j or j >= n take arr[j] = 0. Examples: Input : arr[] = {1, 2, 3, 4, 5}, m = 3 Output : sum_array = {3, 6, 9, 12, 9} Explanation : sum_array[0] = arr[0
7 min read
Construct an Array of size N in which sum of odd elements is equal to sum of even elements
Given an integer N which is always even, the task is to create an array of size N which contains N/2 even numbers and N/2 odd numbers. All the elements of array should be distinct and the sum of even numbers is equal to the sum of odd numbers. If no such array exists then print -1.Examples: Input: N = 8 Output: 2 4 6 8 1 3 5 11 Explanation: The arr
7 min read
Construct the Rooted tree by using start and finish time of its DFS traversal
Given start and finish times of DFS traversal of N vertices that are available in a Rooted tree, the task is to construct the tree (Print the Parent of each node). Parent of the root node is 0.Examples: Input: Start[] = {2, 4, 1, 0, 3}, End[] = {3, 5, 4, 5, 4} Output: 3 4 4 0 3 Given Tree is -: 4(0, 5) / \ (1, 4)3 2(4, 5) / \ (2, 3)1 5(3, 4) The ro
8 min read
Construct BST from its given level order traversal | Set-2
Construct the BST (Binary Search Tree) from its given level order traversal. Examples: Input : {7, 4, 12, 3, 6, 8, 1, 5, 10} Output : BST: 7 / \ 4 12 / \ / 3 6 8 / / \ 1 5 10Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Approach : The idea is to make a struct element NodeDetails which contains a pointer to the
15+ min read
Construct the full k-ary tree from its preorder traversal
Given an array that contains the preorder traversal of the full k-ary tree, construct the full k-ary tree and print its postorder traversal. A full k-ary tree is a tree where each node has either 0 or k children. Examples: Input : preorder[] = {1, 2, 5, 6, 7, 3, 8, 9, 10, 4} k = 3 Output : Postorder traversal of constructed full k-ary tree is: 5 6
10 min read
Construct BST from its given level order traversal
Construct the BST (Binary Search Tree) from its given level order traversal. Examples: Input: arr[] = {7, 4, 12, 3, 6, 8, 1, 5, 10}Output: BST: 7 / \ 4 12 / \ / 3 6 8 / / \1 5 10 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.Construct BST from its given level order traversal Using Recursion:The idea is to use re
15+ min read
Construct Complete Binary Tree from its Linked List Representation
Given the Linked List Representation of a Complete Binary Tree, the task is to construct the complete binary tree. The complete binary tree is represented as a linked list in a way where if the root node is stored at position i, its left, and right children are stored at position 2*i+1, and 2*i+2 respectively. Examples: Input: 1->2->3>4-
10 min read
Construct a matrix with sum equal to the sum of diagonal elements
Given an integer N, the task is to construct a matrix of size N2 using positive and negative integers and excluding 0, such that the sum of the matrix is equal to the sum of the diagonal of the matrix. Examples: Input: N = 2 Output: 1 -2 2 4 Explanation: Diagonal sum = (1 + 4) = 5 Matrix sum = (1 - 2 + 2 + 4) = 5 Input: N = 5 Output: 1 2 3 5 10 3 1
4 min read
Kth smallest positive integer Y such that its sum with X is same as its bitwise OR with X
Given two positive integers X and K, the task is to find the Kth smallest positive integer (Y) such that the sum of X and Y is equal to Bitwise OR of X and Y, i.e. (X + Y = X | Y) Examples: Input: X = 5, K = 1Output: 2Explanation:Consider the smallest number as 2. The sum of 2 and 5 is 2 + 5 = 7 and the Bitwise OR of 2 and 5 is 7. Input: X = 5, K =
6 min read
Queries to check if any pair exists in an array having values at most equal to the given pair
Given a vector of pairs arr[] and Q queries in the form of pairs in an array Queries[], the task for each query is to check if there exists any pair with both the values smaller than those in the pair of the current query. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: arr[][] = {{3, 5}, {2, 7}, {2, 3}, {4, 9}}, Quer
12 min read
Reduce Binary Array by replacing both 0s or both 1s pair with 0 and 10 or 01 pair with 1
Given a binary array arr[] of size N, the task is to find the last number remaining in the array after performing a set of operations. In each operation, select any two numbers and perform the following: If both numbers are the same, remove them from the array and insert a 0.If both numbers are different, remove both of them and insert a 1.Example:
9 min read
Construct array with sum of product of same indexed elements in the given array equal to zero
Given an array, arr[] of size N (always even), the task is to construct a new array consisting of N non-zero integers such that the sum of the product of the same indexed elements of arr[] and the new array is equal to 0. If multiple solutions exist, print any one of them. Examples: Input: arr[] = {1, 2, 3, 4}Output: -4 -3 2 1 Explanation: Sum of p
6 min read
Construct an Array of size N with sum divisible by K and array maximum is minimized
Given integers N and K. The task is to construct an array of size N such that sum of all elements is divisible by K and the maximum element is as minimum as possible. Note: There can be many possible arrays. Printing any one of them is acceptable Examples: Input: N = 1, K = 5Output: 5Explanation: Sum of all elements = 5 and 5 is divisible by 5. Inp
8 min read
Probability of a random pair being the maximum weighted pair
Given two arrays A and B, a random pair is picked having an element from array A and another from array B. Output the probability of the pair being maximum weighted. Examples: Input : A[] = 1 2 3 B[] = 1 3 3 Output : 0.222 Explanation : Possible pairs are : {1, 1}, {1, 3}, {1, 3}, {2, 1}, {2, 3}, {2, 3}, {3, 1}, {3, 3}, {3, 3} i.e. 9. The pair with
7 min read
Count of quadruples with product of a pair equal to the product of the remaining pair
Given an array arr[] of size N, the task is to count the number of unique quadruples (a, b, c, d) from the array such that the product of any pair of elements of the quadruple is equal to the product of the remaining pair of elements. Examples: Input: arr[] = {2, 3, 4, 6}Output: 8Explanation:There are 8 quadruples in the array, i.e. (2, 6, 3, 4), (
7 min read
Generate an N-length array with sum equal to twice the sum of its absolute difference with same-indexed elements of given array
Given an array arr[] of size N, the task is to construct an array brr[] of size N that satisfies the following conditions: In every pair of consecutive elements in the array brr[], one element must be divisible by the other, i.e. brr[i] must be divisible by brr[i + 1] or vice-versa.Every ith element in the array brr[] must satisfy brr[i] >= arr[
5 min read
Construct a distinct elements array with given size, sum and element upper bound
Given N, size of the original array, SUM total sum of all elements present in the array and K such that no element in array is greater than K, construct the original array where all elements in the array are unique. If there is no solution, print "Not Possible". Note: All elements should be positive. Examples: Input: N = 3, SUM = 15, K = 8 Output:
10 min read
Construct the smallest possible Array with given Sum and XOR
Given two positive integers S and X which represents the sum and Bitwise XOR of all the elements of an array arr[]. The task is to find the elements of the array arr[]. If no such array can be generated, print -1.Examples: Input: Sum = 4, Xor = 2 Output: {3, 1} Explanation: Sum of 1 and 3 is 4. Bitwise XOR of 1 and 3 is 2.Input: Sum = 5, Xor = 8 Ou
7 min read
Construct an Array of size N whose sum of cube of all elements is a perfect square
Given an integer N, the tasks is to construct a sorted array arr[] of size N, such that the sum of cube of all elements is a perfect square, i.e. [Tex]\sum_{}A_i^3=X^2 [/Tex], where X is an integer. Examples: Input: N = 5 Output: 1 2 3 4 5 Explanation Sum of cube of all elements = 1 + 8 + 27 + 64 + 125 = 225 which is a perfect square number. Input:
3 min read
Article Tags :