The Wayback Machine - https://web.archive.org/web/20240901154238/https://www.geeksforgeeks.org/difference-array-range-update-query-o1/
Open In App

Difference Array | Range update query in O(1)

Last Updated : 29 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Easy
48.06%
47K

Consider an array A[] of integers and following two types of queries. 

  1. update(l, r, x) : Adds x to all values from A[l] to A[r] (both inclusive).
  2. printArray() : Prints the current modified array.

Examples : 

Input : A [] { 10, 5, 20, 40 }
        update(0, 1, 10)
        printArray()
        update(1, 3, 20)
        update(2, 2, 30)
        printArray()
Output : 20 15 20 40
         20 35 70 60
Explanation : The query update(0, 1, 10) 
adds 10 to A[0] and A[1]. After update,
A[] becomes {20, 15, 20, 40}       
Query update(1, 3, 20) adds 20 to A[1],
A[2] and A[3]. After update, A[] becomes
{20, 35, 40, 60}.
Query update(2, 2, 30) adds 30 to A[2]. 
After update, A[] becomes {20, 35, 70, 60}.

A simple solution is to do following : 

  1. update(l, r, x) : Run a loop from l to r and add x to all elements from A[l] to A[r]
  2. printArray() : Simply print A[].

Time complexities of both of the above operations is O(n)
An efficient solution is to use difference array. 
Difference array D[i] of a given array A[i] is defined as D[i] = A[i]-A[i-1] (for 0 < i < N ) and D[0] = A[0] considering 0 based indexing. Difference array can be used to perform range update queries “l r x” where l is left index, r is right index and x is value to be added and after all queries you can return original array from it. Where update range operations can be performed in O(1) complexity.

  1. update(l, r, x) : Add x to D[l] and subtract it from D[r+1], i.e., we do D[l] += x, D[r+1] -= x
  2. printArray() : Do A[0] = D[0] and print it. For rest of the elements, do A[i] = A[i-1] + D[i] and print them.

Time complexity of update here is improved to O(1). Note that printArray() still takes O(n) time. 

C++




// C++ code to demonstrate Difference Array
#include <bits/stdc++.h>
using namespace std;
  
// Creates a diff array D[] for A[] and returns
// it after filling initial values.
vector<int> initializeDiffArray(vector<int>& A)
{
    int n = A.size();
  
    // We use one extra space because
    // update(l, r, x) updates D[r+1]
    vector<int> D(n + 1);
  
    D[0] = A[0], D[n] = 0;
    for (int i = 1; i < n; i++)
        D[i] = A[i] - A[i - 1];
    return D;
}
  
// Does range update
void update(vector<int>& D, int l, int r, int x)
{
    D[l] += x;
    D[r + 1] -= x;
}
  
// Prints updated Array
int printArray(vector<int>& A, vector<int>& D)
{
    for (int i = 0; i < A.size(); i++) {
        if (i == 0)
            A[i] = D[i];
  
        // Note that A[0] or D[0] decides
        // values of rest of the elements.
        else
            A[i] = D[i] + A[i - 1];
  
        cout << A[i] << " ";
    }
    cout << endl;
}
  
// Driver Code
int main()
{
    // Array to be updated
    vector<int> A{ 10, 5, 20, 40 };
  
    // Create and fill difference Array
    vector<int> D = initializeDiffArray(A);
  
    // After below update(l, r, x), the
    // elements should become 20, 15, 20, 40
    update(D, 0, 1, 10);
    printArray(A, D);
  
    // After below updates, the
    // array should become 20, 35, 70, 60
    update(D, 1, 3, 20);
    update(D, 2, 2, 30);
    printArray(A, D);
  
    return 0;
}


Java




// Java code to demonstrate Difference Array
class GFG {
      
    // Creates a diff array D[] for A[] and returns
    // it after filling initial values.
    static void initializeDiffArray(int A[], int D[])
    {
          
        int n = A.length;
  
        D[0] = A[0];
        D[n] = 0;
        for (int i = 1; i < n; i++)
            D[i] = A[i] - A[i - 1];
    }
  
    // Does range update
    static void update(int D[], int l, int r, int x)
    {
        D[l] += x;
        D[r + 1] -= x;
    }
  
    // Prints updated Array
    static int printArray(int A[], int D[])
    {
        for (int i = 0; i < A.length; i++) {
              
            if (i == 0)
                A[i] = D[i];
  
            // Note that A[0] or D[0] decides
            // values of rest of the elements.
            else
                A[i] = D[i] + A[i - 1];
  
            System.out.print(A[i] + " ");
        }
          
        System.out.println();
          
        return 0;
    }
      
    // Driver Code
    public static void main(String[] args)
    {
        // Array to be updated
        int A[] = { 10, 5, 20, 40 };
        int n = A.length;
        // Create and fill difference Array
        // We use one extra space because
        // update(l, r, x) updates D[r+1]
        int D[] = new int[n + 1];
        initializeDiffArray(A, D);
  
        // After below update(l, r, x), the
        // elements should become 20, 15, 20, 40
        update(D, 0, 1, 10);
        printArray(A, D);
  
        // After below updates, the
        // array should become 30, 35, 70, 60
        update(D, 1, 3, 20);
        update(D, 2, 2, 30);
          
        printArray(A, D);
    }
}
  
// This code is contributed by Anant Agarwal.


Python3




# Python3 code to demonstrate Difference Array
  
# Creates a diff array D[] for A[] and returns
# it after filling initial values.
def initializeDiffArray( A):
    n = len(A)
  
    # We use one extra space because
    # update(l, r, x) updates D[r+1]
    D = [0 for i in range(0 , n + 1)]
  
    D[0] = A[0]; D[n] = 0
      
    for i in range(1, n ):
        D[i] = A[i] - A[i - 1]
    return D
  
  
# Does range update
def update(D, l, r, x):
  
    D[l] += x
    D[r + 1] -= x
  
  
# Prints updated Array
def printArray(A, D):
  
    for i in range(0 , len(A)):
        if (i == 0):
            A[i] = D[i]
  
        # Note that A[0] or D[0] decides
        # values of rest of the elements.
        else:
            A[i] = D[i] + A[i - 1]
  
        print(A[i], end = " ")
      
    print ("")
  
  
# Driver Code
A = [ 10, 5, 20, 40 ]
  
# Create and fill difference Array
D = initializeDiffArray(A)
  
# After below update(l, r, x), the
# elements should become 20, 15, 20, 40
update(D, 0, 1, 10)
printArray(A, D)
  
# After below updates, the
# array should become 30, 35, 70, 60
update(D, 1, 3, 20)
update(D, 2, 2, 30)
printArray(A, D)
  
# This code is contributed by Gitanjali.


C#




// C# code to demonstrate Difference Array
using System;
  
class GFG {
      
    // Creates a diff array D[] for A[] and returns
    // it after filling initial values.
    static void initializeDiffArray(int []A, int []D)
    {
          
        int n = A.Length;
  
        D[0] = A[0];
        D[n] = 0;
        for (int i = 1; i < n; i++)
            D[i] = A[i] - A[i - 1];
    }
  
    // Does range update
    static void update(int []D, int l, int r, int x)
    {
        D[l] += x;
        D[r + 1] -= x;
    }
  
    // Prints updated Array
    static int printArray(int []A, int []D)
    {
        for (int i = 0; i < A.Length; i++) {
              
            if (i == 0)
                A[i] = D[i];
  
            // Note that A[0] or D[0] decides
            // values of rest of the elements.
            else
                A[i] = D[i] + A[i - 1];
  
            Console.Write(A[i] + " ");
        }
          
        Console.WriteLine();
          
        return 0;
    }
      
    // Driver Code
    public static void Main()
    {
        // Array to be updated
        int []A = { 10, 5, 20, 40 };
        int n = A.Length;
        // Create and fill difference Array
        // We use one extra space because
        // update(l, r, x) updates D[r+1]
        int []D = new int[n + 1];
        initializeDiffArray(A, D);
  
        // After below update(l, r, x), the
        // elements should become 20, 15, 20, 40
        update(D, 0, 1, 10);
        printArray(A, D);
  
        // After below updates, the
        // array should become 30, 35, 70, 60
        update(D, 1, 3, 20);
        update(D, 2, 2, 30);
          
        printArray(A, D);
    }
}
  
// This code is contributed by vt_m.


Javascript




<script>
// JavaScript code to demonstrate Difference Array
  
// Creates a diff array D[] for A[] and returns
// it after filling initial values.
function initializeDiffArray( A){
    let n = A.length;
  
    // We use one extra space because
    // update(l, r, x) updates D[r+1]
    let D= [];
  
    D[0] = A[0], D[n] = 0;
    for (let i = 1; i < n; i++)
        D[i] = A[i] - A[i - 1];
    return D;
}
  
// Does range update
function update(D, l, r, x){
    D[l] += x;
    D[r + 1] -= x;
    return D;
}
  
// Prints updated Array
function printArray( A, D){
    for (let i = 0; i < A.length; i++) {
        if (i == 0)
            A[i] = D[i];
  
        // Note that A[0] or D[0] decides
        // values of rest of the elements.
        else
            A[i] = D[i] + A[i - 1];
  
        document.write( A[i]+ " ");
    }
    document.write("<br>");
}
  
// Driver Code
// Array to be updated
let A = [ 10, 5, 20, 40 ];
  
// Create and fill difference Array
let D = initializeDiffArray(A);
  
// After below update(l, r, x), the
// elements should become 20, 15, 20, 40
D = update(D, 0, 1, 10);
printArray(A, D);
  
// After below updates, the
// array should become 30, 35, 70, 60
D = update(D, 1, 3, 20);
D = update(D, 2, 2, 30);
printArray(A, D);
  
</script>


Output: 

20 15 20 40 
20 35 70 60 

Time complexity: O(n)
Auxiliary Space: O(n)
 



Previous Article
Next Article

Similar Reads

Multiplication on Array : Range update query in O(1)
Consider an array A[] of integers and the following two types of queries. update(l, r, x): multiply x to all values from A[l] to A[r] (both inclusive).printArray(): Prints the current modified array. Examples: Input: A[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} update(0, 2, 2) update(1, 4, 3) print() update(4, 8, 5) print() Output: 2 6 6 3 15 5 5 5 5 1 Exp
7 min read
Range and Update Query for Chessboard Pieces
Given N pieces of chessboard all being 'white' and a number of queries Q. There are two types of queries : Update : Given indices of a range [L, R]. Paint all the pieces with their respective opposite color between L and R (i.e. white pieces should be painted with black color and black pieces should be painted with white color).Get : Given indices
15+ min read
Segment Tree | Set 2 (Range Maximum Query with Node Update)
Given an array arr[0 . . . n-1]. Find the maximum of elements from index l to r where 0 &lt;= l &lt;= r &lt;= n-1. Also, change the value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 &lt;= i &lt;= n-1 and then find the maximum element of given range with updated values.Example : Input : {1, 3, 5, 7, 9, 11}
15+ min read
Iterative Segment Tree (Range Maximum Query with Node Update)
Given an array arr[0 . . . n-1]. The task is to perform the following operation: Find the maximum of elements from index l to r where 0 &lt;= l &lt;= r &lt;= n-1.Change value of a specified element of the array to a new value x. Given i and x, change A[i] to x, 0 &lt;= i &lt;= n-1. Examples: Input: a[] = {2, 6, 7, 5, 18, 86, 54, 2} Query1: maximum(
14 min read
Range Update without using Lazy Propagation and Point Query in a Segment Tree
Given an array arr[] consisting of N 0s and a 2D array Q[][] consisting of queries of the following two types: 1 L R X: Increment all the elements in the range [L, R] by X.2 X: Print elements at Xth index of the array. Input: arr[] = { 0, 0, 0, 0, 0 }, Q[][] = { { 1, 0, 2, 100 }, { 2, 1 }, { 1, 2, 3, 200 }, { 2, 2 }, { 4 } } Output: 100 300 0 Expla
13 min read
Binary Indexed Tree : Range Update and Range Queries
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].getRangeSum(l, r): Find the sum of all elements in the array from [l, r].Initially, all the elements in the array are 0. Queries can be in any order, i.e., there can be many updates before range sum. E
15+ min read
Sum of odd Array elements after each update query
Given an integer array Arr[] of length N and an array Queries[] of length Q where Queries[i] = [valuei, indexi]. For each query i, update Arr[indexi] = Arr[indexi] + valuei, then print the sum of the all the odd values of Arr[]. Examples: Input: N = 4, Arr = [1,2,3,5], Q = 4, Queries = [[1,0],[-3,1],[-4,0],[2,3]]Output: 8 7 7 9Explanation: At the b
15+ min read
Range Minimum Query with Range Assignment
There is an array of n elements, initially filled with zeros. The task is to perform q queries from given queries[][] and there are two types of queries: Type 1 (i.e queries[i][0] == 1): Assign value val = queries[i][3] to all elements on the segment l = queries[i][1] to r = queries[i][2].Type 2 (i.e queries[i][0] == 2): Find the minimum on the seg
15+ min read
Segment Tree for Range Addition and Range Minimum Query
Given an array of size N initially filled with 0s. There are Q queries to be performed, and each query can be one of two types: Type 1 (1, L, R, X): Add X to all elements in the segment from L to R−1.Type 2 (2, L, R): Find the minimum value in the segment from L to R−1.Example: Input: n = 5, q = 6, queries = { {1, 0, 3, 3}, {2, 1, 2}, {1, 1, 4, 4},
15+ min read
Mo's Algo with update and without update
Mo's Algorithm is a truly versatile algorithm that finds utility in a vast array of problems requiring querying an array or a list for a subarray. Now, let me tell you, this algorithm owes its efficiency to a very specific order of processing the queries, which significantly reduces the time required to access the array elements. How does Mo's Algo
15+ min read
Update and Print for all the Query
Given an array arr[] of length N consisting of a positive integer, the task is to complete the Q queries and print values accordingly which consists of two types of operations: Operation 1: Update all the indices of the array to its digit sum which lies under the range L and R(0 ? L, R ? N-1).Operation 2: Print the value of the array at that index.
15+ min read
Find element which maximize the XOR value for N given update query
Given arrays Arr[] and Queries[] of size N and an integer K such that (0 ≤ Arr[i], Queries[i] &lt; 2K), the task is to form an array, where each element represents an integer such that XOR of all elements of array and element is maximum by updating Arr[i] with Queries[i] at each step (0 ≤ i ≤ N-1). Examples: Input: N = 4, Arr[] = {2, 3, 4, 7}, Quer
8 min read
Range Update Queries to XOR with 1 in a Binary Array.
Given a binary array arr[] of size N. The task is to answer Q queries which can be of any one type from below: Type 1 - 1 l r : Performs bitwise xor operation on all the array elements from l to r with 1. Type 2 - 2 l r : Returns the minimum distance between two elements with value 1 in a subarray [l, r]. Type 3 - 3 l r : Returns the maximum distan
15+ min read
Queries to update array elements in a range [L, R] to satisfy given conditions
Given an array arr[] consisting of N 0s and an array Q[][] with each row of the form (L, R)., the task for each query is to update all the array elements in the range [L, R] such that arr[i] = i - L + 1. Examples: Input: arr[] = { 0, 0, 0, 0 }, Q[][] = { { 1, 2 }, { 0, 1 } } Output: 1 3 2 0 Explanation: Query1: Updating arr[1] = 1 - 1 + 1, arr[2] =
9 min read
Range Sum and Update in Array : Segment Tree using Stack
Given an array arr[] of N integers. The task is to do the following operations: Add a value X to all the element from index A to B where 0 ? A ? B ? N-1.Find the sum of the element from index L to R where 0 ? L ? R ? N-1 before and after the update given to the array above.Example: Input: arr[] = {1, 3, 5, 7, 9, 11}, L = 1, R = 3, A = 1, B = 5, X =
15+ min read
Range Query on array whose each element is XOR of index value and previous element
Consider an arr[] which can be defined as: You are given Q queries of the form [l, r]. The task is to output the value of arr[l] ? arr[l+1] ? ..... ? arr[r-1] ? arr[r] for each query. Examples : Input : q = 3 q1 = { 2, 4 } q2 = { 2, 8 } q3 = { 5, 9 } Output : 7 9 15 The beginning of the array with constraint look like: arr[] = { 0, 1, 3, 0, 4, 1, 7
9 min read
Print the Array of size N containing values in range [0, M) after Q query updates
Given array arr[] of size N containing cyclic variables having states from 0 to (M - 1) (i.e when incremented from M-1 it goes to 0). The task is to fulfill the Q queries of which are of any of the following two types: 1st Type: 1 L R K - increment all the values in range of indices [L, R], K times cyclically.2nd Type: 2 L R - print the updated val
14 min read
Range Sum Queries and Update with Square Root
Given an array A of N integers and number of queries Q. You have to answer two types of queries. Update [l, r] – for every i in range from l to r update Ai with sqrt(Ai), where sqrt(Ai) represents the square root of Ai in integral form.Query [l, r] – calculate the sum of all numbers ranging between l and r in array A. Prerequisite: Binary Indexed T
13 min read
Range and Update Sum Queries with Factorial
Given an array arr[] of N integers and number of queries Q. The task is to answer three types of queries. Update [l, r] – for every i in range [l, r] increment arr[i] by 1.Update [l, val] – change the value of arr[l] to val.Query [l, r] – calculate the sum of arr[i]! % 109 for all i in range [l, r] where arr[i]! is the factorial of arr[i]. Prerequi
15+ min read
Queries to update a given index and find gcd in range
Given an array arr[] of N integers and queries Q. Queries are of two types: Update a given index ind by X.Find the gcd of the elements in the index range [L, R]. Examples: Input: arr[] = {1, 3, 6, 9, 9, 11} Type 2 query: L = 1, R = 3 Type 1 query: ind = 1, X = 10 Type 2 query: L = 1, R = 3 Output: 3 1 Input: arr[] = {1, 2, 4, 9, 3} Type 2 query: L
15+ min read
Sum of product of all unordered pairs in given range with update queries
Given an array A[] consisting of N integers and Q queries of the below types, the task is to print the output for all the update queries. (1, L, R): The 1st type of query to find the sum of the product of all unordered pairs from index L to R in the array where 1 &lt;= L &lt;= R &lt;= N.(2, P, X): The 2nd type of query to change the value of the Pt
15+ min read
Range sum query using Sparse Table
We have an array arr[]. We need to find the sum of all the elements in the range L and R where 0 &lt;= L &lt;= R &lt;= n-1. Consider a situation when there are many range queries. Examples: Input : 3 7 2 5 8 9 query(0, 5) query(3, 5) query(2, 4) Output : 34 22 15Note : array is 0 based indexed and queries too. Since there are no updates/modificatio
8 min read
Number of prefix sum prime in given range query
Given an array of non-negative integers and range query l, r, find number of prefix sum which are prime numbers in that given range. Prerequisite : Prefix Sum | Primality Test Examples : Input : {2, 3, 4, 7, 9, 10}, l = 1, r = 5; Output : 3 Explanation : prefixSum[0] = arr[l] = 3 prefixSum[1] = prefixSum[0] + arr[2] = 7, prefixSum[2] = prefixSum[1]
9 min read
Range query for count of set bits
Given an array of positive integer and q query which contains two integers, L &amp; R. Task is to find the number of set bits for a given range. Prerequisite : Bitwise Hacks Examples : Input : Arr[] = { 1, 5, 6, 10, 9, 4 } Query : 2 L &amp; R 1 5 2 4 Output : 9 6 Input : Arr[] = { 1, 10, 5, 2, 8, 11, 15 } Query : 2 L &amp; R 2 4 1 5 Output : 4 9 Si
7 min read
Iterative Segment Tree (Range Minimum Query)
We have discussed recursive segment tree implementation. In this post, iterative implementation is discussed.Let us consider the following problem understand Segment Trees. We have an array arr[0 . . . n-1]. We should be able to Find the minimum of elements from index l to r where 0 &lt;= l &lt;= r &lt;= n-1 Change value of a specified element of t
14 min read
Range maximum query using Sparse Table
Given an array arr[], the task is to answer queries to find the maximum of all the elements in the index range arr[L...R].Examples: Input: arr[] = {6, 7, 4, 5, 1, 3}, q[][] = {{0, 5}, {3, 5}, {2, 4}} Output: 7 5 5 Input: arr[] = {3, 34, 1}, q[][] = {{1, 2}} Output: 34 Approach: A similar problem to answer range minimum queries has been discussed he
9 min read
Query to check if a range is made up of consecutive elements
Given an array of n non-consecutive integers and Q queries, the task is to check whether for the given range l and r, the elements are consecutive or not.Examples: Input: arr = { 2, 4, 3, 7, 6, 1}, Q = { (1, 3), (3, 5), (5, 6) } Output: Yes, No, No Explanation: Array elements from (1, 3) = {2, 4, 3}, (3, 5) = {3, 7, 6}, (5, 6) = {6, 1} So the answe
15+ min read
2D Range Minimum Query in O(1)
Given a matrix mat[][] of size N*M, the task is to find the minimum value in a submatrix of the array, defined by the top-left and bottom-right indices of the submatrix for the given queries. Example: Input: N = 4, M = 4, mat[][] = { { 5, 8, 2, 4 }, { 7, 2, 9, 1 }, { 1, 4, 7, 3 }, { 3, 5, 6, 8 } } queries[][] = {{0, 0, 3, 3}, {1, 1, 2, 2}}Output:12
15+ min read
Range query for Largest Sum Contiguous Subarray
Given an array a[] of size N, and Q queries of two types 1 and 2. For the given query of: Type 1: given l and r (they are positions), and task is to print the Largest sum Contiguous Subarray Type 2: given type, index, and value, update aindex = value. Examples: Input: a[] = {-2, -3, 4, -1, -2, 1, 5, -3} 1st query : 1 5 8 2nd query : 2 1 10 3rd quer
15+ min read
Range Minimum Query (Square Root Decomposition and Sparse Table)
We have an array arr[0 . . . n-1]. We should be able to efficiently find the minimum value from index L (query start) to R (query end) where 0 &lt;= L &lt;= R &lt;= n-1. Consider a situation when there are many range queries. Example: Input: arr[] = {7, 2, 3, 0, 5, 10, 3, 12, 18}; query[] = [0, 4], [4, 7], [7, 8]Output: Minimum of [0, 4] is 0 Minim
15+ min read