 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find N’th item in a set formed by sum of two arrays in C++
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
#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
