# Find the Initial Array from given array after range sum queries in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array res[] of size N. Our task is to find the Initial Array from given array after range sum queries.

We need to find the starting array which will return the array rel[] on performing [s, e, val] query on it.

Each [s, e, val] query is solved as

s -> starting index

e -> ending index

val -> update value to be added to each element from s to e in array.

Let's take an example to understand the problem,

Input : rel[] = {7, 4, 8}
Query[][] = {{1, 2, 1},
{0, 1, 3}}
Output : {4, 0, 7}

Explanation

initialArray = {4, 0, 7}; query = {1, 2, 1}; finalArray = {4, 1, 8}
initialArray = {4, 1, 8}; query = {0, 1, 3}; finalArray = {7, 4, 8}

## Solution Approach

A simple solution to the problem is traversing all queries, for all queries solve them using the way we solve it, then at the end return the array found. Here, to find the initialArray, we need to operate it in the opposite way, i.e. subtract it from the given array.

## Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
void calcInitialArrayQueries(int arr[], int n, int query[], int q) {
for (int i = 0; i < q; i++) {
for (int j = query[i];j <= query[i]; j++) {
arr[j] = arr[j] - query[i];
}
}
for (int i = 0; i < n; i++)
cout<<arr[i]<<" ";
}
int main() {
int arr[] = { 5, 1, 8, 2, 9};
int n = sizeof(arr) / sizeof(arr);
int query[] = { {0, 2, -2}, {1, 4, 3}};
int q = sizeof(query) / sizeof(query);
cout<<"Initial array : "; calcInitialArrayQueries(arr, n, query, q);
return 0;
}

## Output

Initial array : 7 0 7 -1 6