Constant time range add operation on an array - GeeksforGeeks

19 Apr, 2021
Given an array of size N which is initialized with all zeros. We are given many ranges add queries, which should be applied to this array. We need to print the final updated array as our result.  
Examples: 
N = 6
Arr = [0, 0, 0, 0, 0, 0]
rangeUpdate1 [0, 2], add 100
Arr = [100, 100, 100, 0, 0, 0]
rangeUpdate1 [1, 5], add 100
Arr = [100, 200, 200, 100, 100, 100]
rangeUpdate1 [2, 3], add 100
Arr = [100, 200, 300, 200, 100, 100]
Which is the final updated array.
This problem can be solved using segment tree with lazy updates in O(log N) time per query but we can do better here, as update operation is not given. We can process each query in constant time using this logic when a query to add V is given in range [a, b] we will add V to arr[a] and –V to arr[b+1] now if we want to get the actual values of the array we will convert the above array into prefix sum array. 
See below example to understand:
Arr = [0, 0, 0, 0, 0, 0]

rangeUpdate1 [0, 2], add 100
Arr = [100, 0, 0, -100, 0, 0]

rangeUpdate1 [1, 5], add 100. 
Arr = [100, 100, 0, -100, 0, 0]
Note: You can not add -100 at 6th index because array length is 6.

rangeUpdate1 [2, 3], add 100
Arr = [100, 100, 100, -100, -100, 0]    

Now we will convert above operation array to prefix sum array as shown below,
Arr = [100, 200, 300, 200, 100, 100]

Which is the final updated array.
So in effect, when we add a value V to specific index of the array, It represents adding V to all elements right to this index, that is why we add –V after range to remove its effect after its range of add query. Please note in below code, if range spans till the last index, the addition of –V is omitted to be in memory limit of the array.  
C++
Java
Python3
C#
PHP
Javascript
//  C++ program to get updated array after many array range// add operation#include <bits/stdc++.h>using namespace std; //  Utility method to add value val, to range [lo, hi]void add(int arr[], int N, int lo, int hi, int val){    arr[lo] += val;    if (hi != N - 1)       arr[hi + 1] -= val;} //  Utility method to get actual array from operation arrayvoid updateArray(int arr[], int N){    //  convert array into prefix sum array    for (int i = 1; i < N; i++)        arr[i] += arr[i - 1];} //  method to print final updated arrayvoid printArr(int arr[], int N){    updateArray(arr, N);    for (int i = 0; i < N; i++)        cout << arr[i] << " ";    cout << endl;} //  Driver codeint main(){    int N = 6;     int arr[N] = {0};     //  Range add Queries    add(arr, N, 0, 2, 100);    add(arr, N, 1, 5, 100);    add(arr, N, 2, 3, 100);     printArr(arr, N);    return 0;}
// Java program to get updated array after// many array range add operationimport java.io.*; class GFG {    // Utility method to add value val,    // to range [lo, hi]    static void add(int arr[], int N, int lo, int hi,                    int val)    {        arr[lo] += val;        if (hi != N - 1)            arr[hi + 1] -= val;    }     // Utility method to get actual array from    // operation array    static void updateArray(int arr[], int N)    {        // convert array into prefix sum array        for (int i = 1; i < N; i++)            arr[i] += arr[i - 1];    }     // method to print final updated array    static void printArr(int arr[], int N)    {        updateArray(arr, N);        for (int i = 0; i < N; i++)            System.out.print("" + arr[i] + " ");        System.out.print("\n");    }     // Driver code    public static void main(String[] args)    {        int N = 6;         int arr[] = new int[N];         // Range add Queries        add(arr, N, 0, 2, 100);        add(arr, N, 1, 5, 100);        add(arr, N, 2, 3, 100);         printArr(arr, N);    }} // This code is contributed by Prakriti Gupta
# Python3 program to get updated array# after many array range add operation # Utility method to add value# val, to range [lo, hi]  def add(arr, N, lo, hi, val):     arr[lo] += val    if (hi != N - 1):        arr[hi + 1] -= val # Utility method to get actual# array from operation array  def updateArray(arr, N):     # convert array into prefix sum array    for i in range(1, N):        arr[i] += arr[i - 1] # method to print final updated array  def printArr(arr, N):     updateArray(arr, N)    for i in range(N):        print(arr[i], end=" ")    print()  # Driver codeN = 6arr = [0 for i in range(N)] # Range add Queriesadd(arr, N, 0, 2, 100)add(arr, N, 1, 5, 100)add(arr, N, 2, 3, 100) printArr(arr, N) # This code is contributed by Anant Agarwal.
// C# program to get updated array after// many array range add operationusing System; class GFG {     // Utility method to add value val,    // to range [lo, hi]    static void add(int[] arr, int N, int lo, int hi,                    int val)    {        arr[lo] += val;        if (hi != N - 1)            arr[hi + 1] -= val;    }     // Utility method to get actual    // array from operation array    static void updateArray(int[] arr, int N)    {        // convert array into        // prefix sum array        for (int i = 1; i < N; i++)            arr[i] += arr[i - 1];    }     // method to print final updated array    static void printArr(int[] arr, int N)    {        updateArray(arr, N);        for (int i = 0; i < N; i++)            Console.Write("" + arr[i] + " ");        Console.Write("\n");    }     // Driver code    public static void Main()    {        int N = 6;         int[] arr = new int[N];         // Range add Queries        add(arr, N, 0, 2, 100);        add(arr, N, 1, 5, 100);        add(arr, N, 2, 3, 100);         printArr(arr, N);    }} // This code is contributed by Nitin Mittal.
<?php// PHP program to get updated array after// many array range add operation // Utility method to add value val,// to range [lo, hi]function add(&$arr, $N, $lo, $hi, $val){    $arr[$lo] += $val;    if ($hi != $N - 1)    $arr[$hi + 1] -= $val;} // Utility method to get actual array// from operation arrayfunction updateArray(&$arr, $N){    // convert array into prefix sum array    for ($i = 1; $i < $N; $i++)        $arr[$i] += $arr[$i - 1];} // method to print final updated arrayfunction printArr(&$arr, $N){    updateArray($arr, $N);    for ($i = 0; $i < $N; $i++)        echo $arr[$i] . " ";    echo "\n";} // Driver Code$N = 6;$arr = array_fill(0, $N, NULL); // Range add Queriesadd($arr, $N, 0, 2, 100);add($arr, $N, 1, 5, 100);add($arr, $N, 2, 3, 100); printArr($arr, $N); // This code is contributed by ita_c?>
<script> // Javascript program to get updated array after// many array range add operation         // Utility method to add value val,    // to range [lo, hi]    function add(arr,N,lo,hi,val)    {        arr[lo] += val;        if (hi != N - 1)            arr[hi + 1] -= val;    }          // Utility method to get actual array from    // operation array    function updateArray(arr,N)    {        // convert array into prefix sum array        for (let i = 1; i < N; i++)            arr[i] += arr[i - 1];    }         // method to print final updated array    function printArr(arr,N)    {        updateArray(arr, N);        for (let i = 0; i < N; i++)            document.write("" + arr[i] + " ");        document.write("<br>");    }         // Driver code    let N = 6;    let arr=new Array(N);    for(let i=0;i<N;i++)    {        arr[i]=0;    }    // Range add Queries    add(arr, N, 0, 2, 100);    add(arr, N, 1, 5, 100);    add(arr, N, 2, 3, 100);     printArr(arr, N);         // This code is contributed by rag2127     </script>
100 200 300 200 100 100 
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nitin mittal
ukasp
PunjPrakash
rag2127
array-range-queries
Directi
Arrays
Directi
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Linear Search
Multidimensional Arrays in Java
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
Queue | Set 1 (Introduction and Array Implementation)
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)