Given an array arr[0..n-1]. The following operations need to be performed.
- update(l, r, val) : Add ‘val’ to all the elements in the array from [l, r].
- getElement(i) : Find element in the array indexed at ‘i’.
Initially all the elements in the array are 0. Queries can be in any order, i.e., there can be many updates before point query.
Example:
Input : arr = {0, 0, 0, 0, 0} Queries: update : l = 0, r = 4, val = 2 getElement : i = 3 update : l = 3, r = 4, val = 3 getElement : i = 3 Output: Element at 3 is 2 Element at 3 is 5 Explanation : Array after first update becomes {2, 2, 2, 2, 2} Array after second update becomes {2, 2, 2, 5, 5}Method 1 [update : O(n), getElement() : O(1)]
- update(l, r, val) : Iterate over the subarray from l to r and increase all the elements by val.
- getElement(i) : To get the element at i’th index, simply return arr[i].
The time complexity in worst case is O(q*n) where q is number of queries and n is number of elements.
Method 2 [update : O(1), getElement() : O(n)]
We can avoid updating all elements and can update only 2 indexes of the array!
- update(l, r, val) : Add ‘val’ to the lth element and subtract ‘val’ from the (r+1)th element, do this for all the update queries.
arr[l] = arr[l] + val arr[r+1] = arr[r+1] - val
- getElement(i) : To get ith element in the array find the sum of all integers in the array from 0 to i.(Prefix Sum).
C++
// C++ program to demonstrate Range Update// and Point Queries Without using BIT#include <bits/stdc++.h>usingnamespacestd;// Updates such that getElement() gets an increased// value when queried from l to r.voidupdate(intarr[],intl,intr,intval){arr[l] += val;arr[r+1] -= val;}// Get the element indexed at iintgetElement(intarr[],inti){// To get ith element sum of all the elements// from 0 to i need to be computedintres = 0;for(intj = 0 ; j <= i; j++)res += arr[j];returnres;}// Driver program to test above functionintmain(){intarr[] = {0, 0, 0, 0, 0};intn =sizeof(arr) /sizeof(arr[0]);intl = 2, r = 4, val = 2;update(arr, l, r, val);//Find the element at Index 4intindex = 4;cout <<"Element at index "<< index <<" is "<<getElement(arr, index) << endl;l = 0, r = 3, val = 4;update(arr,l,r,val);//Find the element at Index 3index = 3;cout <<"Element at index "<< index <<" is "<<getElement(arr, index) << endl;return0;}Java
// Java program to demonstrate Range Update// and Point Queries Without using BITclassGfG {// Updates such that getElement() gets an increased// value when queried from l to r.staticvoidupdate(intarr[],intl,intr,intval){arr[l] += val;if(r +1< arr.length)arr[r+1] -= val;}// Get the element indexed at istaticintgetElement(intarr[],inti){// To get ith element sum of all the elements// from 0 to i need to be computedintres =0;for(intj =0; j <= i; j++)res += arr[j];returnres;}// Driver program to test above functionpublicstaticvoidmain(String[] args){intarr[] = {0,0,0,0,0};intn = arr.length;intl =2, r =4, val =2;update(arr, l, r, val);//Find the element at Index 4intindex =4;System.out.println("Element at index "+ index +" is "+getElement(arr, index));l =0;r =3;val =4;update(arr,l,r,val);//Find the element at Index 3index =3;System.out.println("Element at index "+ index +" is "+getElement(arr, index));}}Python3
# Python3 program to demonstrate Range# Update and PoQueries Without using BIT# Updates such that getElement() gets an# increased value when queried from l to r.defupdate(arr, l, r, val):arr[l]+=valifr+1<len(arr):arr[r+1]-=val# Get the element indexed at idefgetElement(arr, i):# To get ith element sum of all the elements# from 0 to i need to be computedres=0forjinrange(i+1):res+=arr[j]returnres# Driver Codeif__name__=='__main__':arr=[0,0,0,0,0]n=len(arr)l=2r=4val=2update(arr, l, r, val)# Find the element at Index 4index=4print("Element at index", index,"is", getElement(arr, index))l=0r=3val=4update(arr, l, r, val)# Find the element at Index 3index=3print("Element at index", index,"is", getElement(arr, index))# This code is contributed by PranchalKC#
// C# program to demonstrate Range Update// and Point Queries Without using BITusingSystem;classGfG{// Updates such that getElement()// gets an increased value when// queried from l to r.staticvoidupdate(int[]arr,intl,intr,intval){arr[l] += val;if(r + 1 < arr.Length)arr[r + 1] -= val;}// Get the element indexed at istaticintgetElement(int[]arr,inti){// To get ith element sum of all the elements// from 0 to i need to be computedintres = 0;for(intj = 0 ; j <= i; j++)res += arr[j];returnres;}// Driver codepublicstaticvoidMain(String[] args){int[]arr = {0, 0, 0, 0, 0};intn = arr.Length;intl = 2, r = 4, val = 2;update(arr, l, r, val);//Find the element at Index 4intindex = 4;Console.WriteLine("Element at index "+index +" is "+getElement(arr, index));l = 0;r = 3;val = 4;update(arr,l,r,val);//Find the element at Index 3index = 3;Console.WriteLine("Element at index "+index +" is "+getElement(arr, index));}}// This code is contributed by PrinciRaj1992PHP
<?php// PHP program to demonstrate Range Update// and Point Queries Without using BIT// Updates such that getElement() gets an// increased value when queried from l to r.functionupdate(&$arr,$l,$r,$val){$arr[$l] +=$val;if($r+ 1 < sizeof($arr))$arr[$r+ 1] -=$val;}// Get the element indexed at ifunctiongetElement(&$arr,$i){// To get ith element sum of all the elements// from 0 to i need to be computed$res= 0;for($j= 0 ;$j<=$i;$j++)$res+=$arr[$j];return$res;}// Driver Code$arr=array(0, 0, 0, 0, 0);$n= sizeof($arr);$l= 2;$r= 4;$val= 2;update($arr,$l,$r,$val);// Find the element at Index 4$index= 4;echo("Element at index ".$index." is ". getElement($arr,$index) ."\n");$l= 0;$r= 3;$val= 4;update($arr,$l,$r,$val);// Find the element at Index 3$index= 3;echo("Element at index ".$index." is ". getElement($arr,$index));// This code is contributed by Code_Mech?>
Output:Element at index 4 is 2 Element at index 3 is 6
Time complexity : O(q*n) where q is number of queries.
Method 3 (Using Binary Indexed Tree)
In method 2, we have seen that the problem can reduced to update and prefix sum queries. We have seen that BIT can be used to do update and prefix sum queries in O(Logn) time.
Below is the implementation.
C++
// C++ code to demonstrate Range Update and// Point Queries on a Binary Index Tree#include <bits/stdc++.h>usingnamespacestd;// Updates a node in Binary Index Tree (BITree) at given index// in BITree. The given value 'val' is added to BITree[i] and// all of its ancestors in tree.voidupdateBIT(intBITree[],intn,intindex,intval){// index in BITree[] is 1 more than the index in arr[]index = index + 1;// Traverse all ancestors and add 'val'while(index <= n){// Add 'val' to current node of BI TreeBITree[index] += val;// Update index to that of parent in update Viewindex += index & (-index);}}// Constructs and returns a Binary Indexed Tree for given// array of size n.int*constructBITree(intarr[],intn){// Create and initialize BITree[] as 0int*BITree =newint[n+1];for(inti=1; i<=n; i++)BITree[i] = 0;// Store the actual values in BITree[] using update()for(inti=0; i<n; i++)updateBIT(BITree, n, i, arr[i]);// Uncomment below lines to see contents of BITree[]//for (int i=1; i<=n; i++)// cout << BITree[i] << " ";returnBITree;}// SERVES THE PURPOSE OF getElement()// Returns sum of arr[0..index]. This function assumes// that the array is preprocessed and partial sums of// array elements are stored in BITree[]intgetSum(intBITree[],intindex){intsum = 0;// Iniialize result// index in BITree[] is 1 more than the index in arr[]index = index + 1;// Traverse ancestors of BITree[index]while(index>0){// Add current element of BITree to sumsum += BITree[index];// Move index to parent node in getSum Viewindex -= index & (-index);}returnsum;}// Updates such that getElement() gets an increased// value when queried from l to r.voidupdate(intBITree[],intl,intr,intn,intval){// Increase value at 'l' by 'val'updateBIT(BITree, n, l, val);// Decrease value at 'r+1' by 'val'updateBIT(BITree, n, r+1, -val);}// Driver program to test above functionintmain(){intarr[] = {0, 0, 0, 0, 0};intn =sizeof(arr)/sizeof(arr[0]);int*BITree = constructBITree(arr, n);// Add 2 to all the element from [2,4]intl = 2, r = 4, val = 2;update(BITree, l, r, n, val);// Find the element at Index 4intindex = 4;cout <<"Element at index "<< index <<" is "<<getSum(BITree,index) <<"\n";// Add 2 to all the element from [0,3]l = 0, r = 3, val = 4;update(BITree, l, r, n, val);// Find the element at Index 3index = 3;cout <<"Element at index "<< index <<" is "<<getSum(BITree,index) <<"\n";return0;}Java
/* Java code to demonstrate Range Update and* Point Queries on a Binary Index Tree.* This method only works when all array* values are initially 0.*/classGFG{// Max tree sizefinalstaticintMAX =1000;staticintBITree[] =newint[MAX];// Updates a node in Binary Index// Tree (BITree) at given index// in BITree. The given value 'val'// is added to BITree[i] and// all of its ancestors in tree.publicstaticvoidupdateBIT(intn,intindex,intval){// index in BITree[] is 1// more than the index in arr[]index = index +1;// Traverse all ancestors// and add 'val'while(index <= n){// Add 'val' to current// node of BITreeBITree[index] += val;// Update index to that// of parent in update Viewindex += index & (-index);}}// Constructs Binary Indexed Tree// for given array of size n.publicstaticvoidconstructBITree(intarr[],intn){// Initialize BITree[] as 0for(inti =1; i <= n; i++)BITree[i] =0;// Store the actual values// in BITree[] using update()for(inti =0; i < n; i++)updateBIT(n, i, arr[i]);// Uncomment below lines to// see contents of BITree[]// for (int i=1; i<=n; i++)// cout << BITree[i] << " ";}// SERVES THE PURPOSE OF getElement()// Returns sum of arr[0..index]. This// function assumes that the array is// preprocessed and partial sums of// array elements are stored in BITree[]publicstaticintgetSum(intindex){intsum =0;//Initialize result// index in BITree[] is 1 more// than the index in arr[]index = index +1;// Traverse ancestors// of BITree[index]while(index >0){// Add current element// of BITree to sumsum += BITree[index];// Move index to parent// node in getSum Viewindex -= index & (-index);}// Return the sumreturnsum;}// Updates such that getElement()// gets an increased value when// queried from l to r.publicstaticvoidupdate(intl,intr,intn,intval){// Increase value at// 'l' by 'val'updateBIT(n, l, val);// Decrease value at// 'r+1' by 'val'updateBIT(n, r +1, -val);}// Driver Codepublicstaticvoidmain(String args[]){intarr[] = {0,0,0,0,0};intn = arr.length;constructBITree(arr,n);// Add 2 to all the// element from [2,4]intl =2, r =4, val =2;update(l, r, n, val);intindex =4;System.out.println("Element at index "+index +" is "+getSum(index));// Add 2 to all the// element from [0,3]l =0; r =3; val =4;update(l, r, n, val);// Find the element// at Index 3index =3;System.out.println("Element at index "+index +" is "+getSum(index));}}// This code is contributed// by Puneet Kumar.Python3
# Python3 code to demonstrate Range Update and# PoQueries on a Binary Index Tree# Updates a node in Binary Index Tree (BITree) at given index# in BITree. The given value 'val' is added to BITree[i] and# all of its ancestors in tree.defupdateBIT(BITree, n, index, val):# index in BITree[] is 1 more than the index in arr[]index=index+1# Traverse all ancestors and add 'val'while(index <=n):# Add 'val' to current node of BI TreeBITree[index]+=val# Update index to that of parent in update Viewindex+=index & (-index)# Constructs and returns a Binary Indexed Tree for given# array of size n.defconstructBITree(arr, n):# Create and initialize BITree[] as 0BITree=[0]*(n+1)# Store the actual values in BITree[] using update()foriinrange(n):updateBIT(BITree, n, i, arr[i])returnBITree# SERVES THE PURPOSE OF getElement()# Returns sum of arr[0..index]. This function assumes# that the array is preprocessed and partial sums of# array elements are stored in BITree[]defgetSum(BITree, index):sum=0# Iniialize result# index in BITree[] is 1 more than the index in arr[]index=index+1# Traverse ancestors of BITree[index]while(index >0):# Add current element of BITree to sumsum+=BITree[index]# Move index to parent node in getSum Viewindex-=index & (-index)returnsum# Updates such that getElement() gets an increased# value when queried from l to r.defupdate(BITree, l, r, n, val):# Increase value at 'l' by 'val'updateBIT(BITree, n, l, val)# Decrease value at 'r+1' by 'val'updateBIT(BITree, n, r+1,-val)# Driver codearr=[0,0,0,0,0]n=len(arr)BITree=constructBITree(arr, n)# Add 2 to all the element from [2,4]l=2r=4val=2update(BITree, l, r, n, val)# Find the element at Index 4index=4print("Element at index", index,"is", getSum(BITree, index))# Add 2 to all the element from [0,3]l=0r=3val=4update(BITree, l, r, n, val)# Find the element at Index 3index=3print("Element at index", index,"is", getSum(BITree,index))# This code is contributed by mohit kumar 29C#
usingSystem;/* C# code to demonstrate Range Update and* Point Queries on a Binary Index Tree.* This method only works when all array* values are initially 0.*/publicclassGFG{// Max tree sizepublicconstintMAX = 1000;publicstaticint[] BITree =newint[MAX];// Updates a node in Binary Index// Tree (BITree) at given index// in BITree. The given value 'val'// is added to BITree[i] and// all of its ancestors in tree.publicstaticvoidupdateBIT(intn,intindex,intval){// index in BITree[] is 1// more than the index in arr[]index = index + 1;// Traverse all ancestors// and add 'val'while(index <= n){// Add 'val' to current// node of BITreeBITree[index] += val;// Update index to that// of parent in update Viewindex += index & (-index);}}// Constructs Binary Indexed Tree// for given array of size n.publicstaticvoidconstructBITree(int[] arr,intn){// Initialize BITree[] as 0for(inti = 1; i <= n; i++){BITree[i] = 0;}// Store the actual values// in BITree[] using update()for(inti = 0; i < n; i++){updateBIT(n, i, arr[i]);}// Uncomment below lines to// see contents of BITree[]// for (int i=1; i<=n; i++)// cout << BITree[i] << " ";}// SERVES THE PURPOSE OF getElement()// Returns sum of arr[0..index]. This// function assumes that the array is// preprocessed and partial sums of// array elements are stored in BITree[]publicstaticintgetSum(intindex){intsum = 0;//Initialize result// index in BITree[] is 1 more// than the index in arr[]index = index + 1;// Traverse ancestors// of BITree[index]while(index > 0){// Add current element// of BITree to sumsum += BITree[index];// Move index to parent// node in getSum Viewindex -= index & (-index);}// Return the sumreturnsum;}// Updates such that getElement()// gets an increased value when// queried from l to r.publicstaticvoidupdate(intl,intr,intn,intval){// Increase value at// 'l' by 'val'updateBIT(n, l, val);// Decrease value at// 'r+1' by 'val'updateBIT(n, r + 1, -val);}// Driver CodepublicstaticvoidMain(string[] args){int[] arr =newint[] {0, 0, 0, 0, 0};intn = arr.Length;constructBITree(arr,n);// Add 2 to all the// element from [2,4]intl = 2, r = 4, val = 2;update(l, r, n, val);intindex = 4;Console.WriteLine("Element at index "+ index +" is "+ getSum(index));// Add 2 to all the// element from [0,3]l = 0;r = 3;val = 4;update(l, r, n, val);// Find the element// at Index 3index = 3;Console.WriteLine("Element at index "+ index +" is "+ getSum(index));}}// This code is contributed by Shrikant13Output:
Element at index 4 is 2 Element at index 3 is 6
Time Complexity : O(q * log n) + O(n * log n) where q is number of queries.
Method 1 is efficient when most of the queries are getElement(), method 2 is efficient when most of the queries are updates() and method 3 is preferred when there is mix of both queries.
This article is contributed by Chirag Agarwal. 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.



