# Find N’th item in a set formed by sum of two arrays in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two sorted arrays arr1[] and arr2[] of size m and an element N. Our task is to Find Nth item in a set formed by the sum of two arrays.

Code description − Here, we will create a set that consists of the sum of element one of arr1 and one of arr2 i.e. sum = arr1[i] + arr2[j], where are i , j < m. For N, we need to find the value of the Nth element of the set.

Let’s take an example to understand the problem,

## Input

arr1[] = {3, 1, 5} , arr2[] = {6, 2, 8} , N = 4

Output

## Explanation

The elements of the set are −

9 (3+6 and 1 +8) , 5 (3 + 2) , 11 (3+8, 5+6), 7 (1+6, 5+2), 3 (1+2), 13 (5+8).
The fourth element is 7.

## Solution Approach

The solution approach is simply finding the elements of the set by finding the sum of elements of the arrays. For this, we will use nested loops, outer loop to iterate elements of arr1 and the inner loop to iterate the elements of arr2. And for each iteration of the inner loop, we will store the sum to the set, which will not allow duplicate elements. After all sum values are feeded, we will traverse the set and return the Nth element.

Program to illustrate the working of our solution,

## Example

Live Demo

#include <iostream>
using namespace std;
void calcSumVariables(int sum[], int n) {
float SUMX = 0;
for (int i = 0; i < n; i++) {
SUMX += sum[i];
}
SUMX /= (n - 1);
for (int i = 0; i < n; i++)
cout<<"\nx"<<(i + 1)<<" = "<<(SUMX - sum[i]);
}
int main(){
int sum[] = {3, 8, 6, 7, 4, 5, 9 };
int N = sizeof(sum) / sizeof(sum[0]);
cout<<"The value of variables that form the sum are ";
calcSumVariables(sum, N);
return 0;
}

## Output

The value of variables that form the sum are
x1 = 4
x2 = -1
x3 = 1
x4 = 0
x5 = 3
x6 = 2
x7 = -2
Published on 13-Mar-2021 12:29:09