Range Addition in C++


Suppose we have an array of size n and that is initialized with 0's and we also have a value k, we will perform k update operations. Each operation will be represented as triplet: [startIndex, endIndex, inc] which increments each element of subarray A[startIndex ... endIndex] (startIndex and endIndex inclusive) with inc. We have to find the modified array after all k operations were executed.

So, if the input is like length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]], then the output will be [- 2,0,3,5,3]

To solve this, we will follow these steps −

  • Define an array ret of size n

  • for initialize i := 0, when i < size of a, update (increase i by 1), do −

    • l := a[i, 0]

    • r := a[i, 1] + 1

    • ret[l] := ret[l] + a[i, 2]

    • if r < n, then −

      • ret[r] := ret[r] - a[i, 2]

  • for initialize i := 1, when i < n, update (increase i by 1), do −

    • ret[i] := ret[i] + ret[i - 1]

  • return ret

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto< v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector<int< getModifiedArray(int n, vector& a) {
      vector<int< ret(n);
      for (int i = 0; i < a.size(); i++) {
         int l = a[i][0];
         int r = a[i][1] + 1;
         ret[l] += a[i][2];
         if (r < n) {
            ret[r] -= a[i][2];
         }
      }
      for (int i = 1; i < n; i++) {
         ret[i] += ret[i - 1];
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<vector<int<> v = {{1,3,2},{2,4,3},{0,2,-2}};
   print_vector(ob.getModifiedArray(5,v));
}

Input

5, {{1,3,2},{2,4,3},{0,2,-2}}

Output

[-2, 0, 3, 5, 3, ]

Updated on: 19-Nov-2020

124 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements