
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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 Initial Array from Given Array After Range Sum Queries in C++
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[][3], int q) { for (int i = 0; i < q; i++) { for (int j = query[i][0];j <= query[i][1]; j++) { arr[j] = arr[j] - query[i][2]; } } 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[0]); int query[][3] = { {0, 2, -2}, {1, 4, 3}}; int q = sizeof(query) / sizeof(query[0]); cout<<"Initial array : "; calcInitialArrayQueries(arr, n, query, q); return 0; }
Output
Initial array : 7 0 7 -1 6