

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 the 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
- Related Questions & Answers
- Maximum subarray sum after dividing array into subarrays based on the given queries in Java
- Array sum after dividing numbers from previous?
- Min-Max Range Queries in Array in C++
- Queries for counts of array elements with values in given range in C++
- Construct sum-array with sum of elements in given range in C++
- Array sum after dividing numbers from previous in C?
- Queries for bitwise AND in the index range [L, R] of the given Array using C++
- Queries for Bitwise OR in the Index Range [L, R] of the Given Array using C++
- Find the Number Whose Sum of XOR with Given Array Range is Maximum using C++
- Binary array after M range toggle operations?
- How to find the target sum from the given array by backtracking using C#?
- Range Sum Queries Without Updates using C++
- C++ Program for the Range sum queries without updates?
- Sum of Even Numbers After Queries in Python
- C++ code to find array from given array with conditions