Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Range sum query using Sparse Table
Next article icon

Difference Array | Range update query in O(1)

Last Updated : 05 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

You are given an integer array arr[] and a list of queries. Each query is represented as a list of integers where:

  • [1, l, r, x]: Adds x to all elements from arr[l] to arr[r] (inclusive).
  • [2]: Prints the current state of the array.

You need to perform the queries in order.

Examples : 

Input: arr[] = [10, 5, 20, 40], queries = [ [1, 0, 1, 10], [2], [1, 1, 3, 20], [1, 2, 2, 30], [2] ]
Output: 20 15 20 40
20 35 70 60

Explanation: [1, 0, 1, 10]: Adds 10 to arr[0] and arr[1].
Array becomes [20, 15, 20, 40].

  • (2): Prints the array: 20 15 20 40.
  • [1, 1, 3, 20)]: Adds 20 to arr[1], arr[2], and arr[3].
    Array becomes [20, 35, 40, 60].
  • [1, 2, 2, 30]: Adds 30 to arr[2].
    Array becomes [20, 35, 70, 60].
  • (2): Prints the array: 20 35 70 60.

Table of Content

  • [Naive Approach] Using loops for each queries - O(n * q) time and O(1) space
  • [Expected Approach] Using Difference Array

[Naive Approach] Using loops for each queries - O(n * q) time and O(1) space

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 arr[l] to arr[r]
  2. printArray() : Simply print arr[].
C++
#include <iostream> #include <vector> using namespace std;  void update(vector<int> &arr, int l, int r, int x) {     for (int i = l; i <= r; i++)     {         arr[i] += x;     } }  void printArray(const vector<int> &arr) {     for (int num : arr)     {         cout << num << " ";     }     cout << endl; }  int main() {     vector<int> arr = {10, 5, 20, 40};      vector<vector<int>> queries = {{1, 0, 1, 10}, {2}, {1, 1, 3, 20}, {1, 2, 2, 30}, {2}};      for (const auto &query : queries)     {         if (query[0] == 1)         {             // update operation             int l = query[1];             int r = query[2];             int x = query[3];             update(arr, l, r, x);         }         else if (query[0] == 2)         {             // print operation             printArray(arr);         }     }      return 0; } 
Java
import java.util.Arrays; import java.util.List;  public class GfG{     public static void update(int[] arr, int l, int r,                               int x)     {         for (int i = l; i <= r; i++) {             arr[i] += x;         }     }      public static void printArray(int[] arr)     {         for (int num : arr) {             System.out.print(num + " ");         }         System.out.println();     }      public static void main(String[] args)     {         int[] arr = { 10, 5, 20, 40 };          int[][] queries = { { 1, 0, 1, 10 },                             { 2 },                             { 1, 1, 3, 20 },                             { 1, 2, 2, 30 },                             { 2 } };          for (int[] query : queries) {             if (query[0] == 1) {                 // update operation                 int l = query[1];                 int r = query[2];                 int x = query[3];                 update(arr, l, r, x);             }             else if (query[0] == 2) {                 // print operation                 printArray(arr);             }         }     } } 
Python
def update(arr, l, r, x):     for i in range(l, r + 1):         arr[i] += x   def print_array(arr):     print(' '.join(map(str, arr)))   if __name__ == '__main__':     arr = [10, 5, 20, 40]      queries = [[1, 0, 1, 10], [2], [1, 1, 3, 20], [1, 2, 2, 30], [2]]      for query in queries:         if query[0] == 1:             # update operation             l, r, x = query[1], query[2], query[3]             update(arr, l, r, x)         elif query[0] == 2:             # print operation             print_array(arr) 
C#
using System; using System.Collections.Generic;  class GfG{     static void Update(int[] arr, int l, int r, int x)     {         for (int i = l; i <= r; i++) {             arr[i] += x;         }     }      static void PrintArray(int[] arr)     {         foreach(int num in arr)         {             Console.Write(num + " ");         }         Console.WriteLine();     }      static void Main()     {         int[] arr = new int[] { 10, 5, 20, 40 };          List<List<int>> queries = new List<List<int>>{             new List<int>{ 1, 0, 1, 10 },             new List<int>{ 2 },             new List<int>{ 1, 1, 3, 20 },             new List<int>{ 1, 2, 2, 30 }, new List<int>{ 2 }         };          foreach(var query in queries)         {             if (query[0] == 1) {                 // update operation                 int l = query[1];                 int r = query[2];                 int x = query[3];                 Update(arr, l, r, x);             }             else if (query[0] == 2) {                 // print operation                 PrintArray(arr);             }         }     } } 
JavaScript
function update(arr, l, r, x) {     for (let i = l; i <= r; i++) {         arr[i] += x;     } }  function printArray(arr) { console.log(arr.join(" ")); }  const arr = [ 10, 5, 20, 40 ];  const queries = [     [ 1, 0, 1, 10 ], [ 2 ], [ 1, 1, 3, 20 ],     [ 1, 2, 2, 30 ], [ 2 ] ];  queries.forEach(query => {     if (query[0] === 1) {         // update operation         const [_, l, r, x] = query;         update(arr, l, r, x);     }     else if (query[0] === 2) {         // print operation         printArray(arr);     } }); 

Output
20 15 20 40  20 35 70 60  

Time Complexity: O(n * q), O(n) for each queries
Space Complexity: O(1)

[Expected Approach] Using Difference Array

Difference array d[i] of a given array arr[i] is defined as d[i] = arr[i] - arr[i-1] (for 0 < i < n) and d[0] = arr[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 arr[i] = arr[i-1] + d[i] and print them.

Illustration: Let us understand this with an example arr = [2, 5, 7, 9, 6]. The difference array would be d = [2, 3, 2, 2, -3]. After an update say update(1, 3, 4), we add 4 to index 1 and subtract from index 4, the difference array would become d = [2, 7, 2, 2, -7]. Now to print array, we print 2, 2 + 7 = 9, 9 + 2 = 11, 11 + 2 = 13, 13 + (-7) = 6

C++
#include <iostream> #include <vector> using namespace std;  vector<int> initDiffArray(vector<int> &arr) {     int n = arr.size();      // Initialize difference array with an extra element     vector<int> d(n + 1, 0);      d[0] = arr[0];     for (int i = 1; i < n; i++)     {         d[i] = arr[i] - arr[i - 1];     }     return d; }  void update(vector<int> &d, int l, int r, int x) {     d[l] += x;     d[r + 1] -= x; }  void printArray(vector<int> &arr, vector<int> &d) {     for (int i = 0; i < arr.size(); i++)     {         if (i == 0)             arr[i] = d[i];         else             arr[i] = d[i] + arr[i - 1];          cout << arr[i] << " ";     }     cout << endl; }  int main() {     vector<int> arr{10, 5, 20, 40};      vector<int> d = initDiffArray(arr);      vector<vector<int>> queries = {{1, 0, 1, 10}, {2}, {1, 1, 3, 20}, {1, 2, 2, 30}, {2}};      for (const auto &query : queries)     {         if (query[0] == 1)         {             // If it's an update query: update(l, r, x)             int l = query[1];             int r = query[2];             int x = query[3];             update(d, l, r, x);         }         else if (query[0] == 2)         {             // If it's a print query: printArray()             printArray(arr, d);         }     }      return 0; } 
Java
import java.util.Arrays; import java.util.List; import java.util.ArrayList;  public class GfG{     public static int[] initDiffArray(int[] arr) {         int n = arr.length;         int[] d = new int[n + 1];         d[0] = arr[0];         for (int i = 1; i < n; i++) {             d[i] = arr[i] - arr[i - 1];         }         return d;     }      public static void update(int[] d, int l, int r, int x) {         d[l] += x;         d[r + 1] -= x;     }      public static void printArray(int[] arr, int[] d) {         for (int i = 0; i < arr.length; i++) {             if (i == 0)                 arr[i] = d[i];             else                 arr[i] = d[i] + arr[i - 1];             System.out.print(arr[i] + " ");         }         System.out.println();     }      public static void main(String[] args) {         int[] arr = {10, 5, 20, 40};         int[] d = initDiffArray(arr);         List<int[]> queries = new ArrayList<>();         queries.add(new int[]{1, 0, 1, 10});         queries.add(new int[]{2});         queries.add(new int[]{1, 1, 3, 20});         queries.add(new int[]{1, 2, 2, 30});         queries.add(new int[]{2});          for (int[] query : queries) {             if (query[0] == 1) {                 // If it's an update query: update(l, r, x)                 int l = query[1];                 int r = query[2];                 int x = query[3];                 update(d, l, r, x);             } else if (query[0] == 2) {                 // If it's a print query: printArray()                 printArray(arr, d);             }         }     } } 
Python
def init_diff_array(arr):     n = len(arr)     d = [0] * (n + 1)     d[0] = arr[0]     for i in range(1, n):         d[i] = arr[i] - arr[i - 1]     return d   def update(d, l, r, x):     d[l] += x     d[r + 1] -= x   def print_array(arr, d):     for i in range(len(arr)):         if i == 0:             arr[i] = d[i]         else:             arr[i] = d[i] + arr[i - 1]         print(arr[i], end=' ')     print()   if __name__ == '__main__':     arr = [10, 5, 20, 40]     d = init_diff_array(arr)     queries = [[1, 0, 1, 10], [2], [1, 1, 3, 20], [1, 2, 2, 30], [2]]      for query in queries:         if query[0] == 1:             # If it's an update query: update(l, r, x)             l, r, x = query[1], query[2], query[3]             update(d, l, r, x)         elif query[0] == 2:             # If it's a print query: print_array()             print_array(arr, d) 
C#
using System; using System.Collections.Generic;  class GfG{     static int[] InitDiffArray(int[] arr)     {         int n = arr.Length;         int[] d = new int[n + 1];         d[0] = arr[0];         for (int i = 1; i < n; i++) {             d[i] = arr[i] - arr[i - 1];         }         return d;     }      static void Update(int[] d, int l, int r, int x)     {         d[l] += x;         d[r + 1] -= x;     }      static void PrintArray(int[] arr, int[] d)     {         for (int i = 0; i < arr.Length; i++) {             if (i == 0)                 arr[i] = d[i];             else                 arr[i] = d[i] + arr[i - 1];             Console.Write(arr[i] + " ");         }         Console.WriteLine();     }      static void Main()     {         int[] arr = { 10, 5, 20, 40 };         int[] d = InitDiffArray(arr);         List<int[]> queries = new List<int[]>{             new int[] { 1, 0, 1, 10 }, new int[] { 2 },             new int[] { 1, 1, 3, 20 },             new int[] { 1, 2, 2, 30 }, new int[] { 2 }         };          foreach(var query in queries)         {             if (query[0] == 1) {                 // If it's an update query: update(l, r, x)                 int l = query[1];                 int r = query[2];                 int x = query[3];                 Update(d, l, r, x);             }             else if (query[0] == 2) {                 // If it's a print query: printArray()                 PrintArray(arr, d);             }         }     } } 
JavaScript
function initDiffArray(arr) {     const n = arr.length;     const d = new Array(n + 1).fill(0);     d[0] = arr[0];     for (let i = 1; i < n; i++) {         d[i] = arr[i] - arr[i - 1];     }     return d; }  function update(d, l, r, x) {     d[l] += x;     d[r + 1] -= x; }  function printArray(arr, d) {     for (let i = 0; i < arr.length; i++) {         if (i === 0)             arr[i] = d[i];         else             arr[i] = d[i] + arr[i - 1];         process.stdout.write(arr[i] + " ");     }     console.log(); }  const arr = [ 10, 5, 20, 40 ]; const d = initDiffArray(arr); const queries = [     [ 1, 0, 1, 10 ], [ 2 ], [ 1, 1, 3, 20 ],     [ 1, 2, 2, 30 ], [ 2 ] ];  queries.forEach(query => {     if (query[0] === 1) {         // If it's an update query: update(l, r, x)         const l = query[1];         const r = query[2];         const x = query[3];         update(d, l, r, x);     }     else if (query[0] === 2) {         // If it's a print query: printArray()         printArray(arr, d);     } }); 

Output: 

20 15 20 40  20 35 70 60 

Time complexity:
For update here is improved to O(1).
For printArray() still takes O(n) time. 
Auxiliary Space: O(n)


Next Article
Range sum query using Sparse Table

G

garg_ak0109
Improve
Article Tags :
  • Misc
  • Advanced Data Structure
  • DSA
  • Arrays
  • array-range-queries
Practice Tags :
  • Advanced Data Structure
  • Arrays
  • Misc

Similar Reads

    PreComputation Technique on Arrays
    Precomputation refers to the process of pre-calculating and storing the results of certain computations or data structures(array in this case) in advance, in order to speed up the execution time of a program. This can be useful in situations where the same calculations are needed multiple times, as
    15 min read
    Queries for the product of first N factorials
    Given Q[] queries where each query consists of an integer N, the task is to find the product of first N factorials for each of the query. Since the result could be large, compute it modulo 109 + 7.Examples: Input: Q[] = {4, 5} Output: 288 34560 Query 1: 1! * 2! * 3! * 4! = 1 * 2 * 6 * 24 = 288 Query
    7 min read
    Range sum queries without updates
    Given an array arr of integers of size n. We need to compute the sum of elements from index i to index j. The queries consisting of i and j index values will be executed multiple times.Examples: Input : arr[] = {1, 2, 3, 4, 5} i = 1, j = 3 i = 2, j = 4Output : 9 12 Input : arr[] = {1, 2, 3, 4, 5} i
    6 min read
    Range Queries for Frequencies of array elements
    Given an array of n non-negative integers. The task is to find frequency of a particular element in the arbitrary range of array[]. The range is given as positions (not 0 based indexes) in array. There can be multiple queries of given type. Examples: Input : arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; lef
    13 min read
    Count Primes in Ranges
    Given a 2d array queries[][] of size n, where each query queries[i] contain 2 elements [l, r], your task is to find the count of number of primes in inclusive range [l, r]Examples: Input: queries[][] = [ [1, 10], [5, 10], [11, 20] ]Output: 4 2 4Explanation: For query 1, number of primes in range [1,
    12 min read
    Check in binary array the number represented by a subarray is odd or even
    Given an array such that all its terms is either 0 or 1.You need to tell the number represented by a subarray a[l..r] is odd or even Examples : Input : arr = {1, 1, 0, 1} l = 1, r = 3 Output : odd number represented by arr[l...r] is 101 which 5 in decimal form which is odd Input : arr = {1, 1, 1, 1}
    4 min read
    GCDs of given index ranges in an Array
    Given an array arr[] of size N and Q queries of type {qs, qe} where qs and qe denote the starting and ending index of the query, the task is to find the GCD of all the numbers in the range. Examples: Input: arr[] = {2, 3, 60, 90, 50};Index Ranges: {1, 3}, {2, 4}, {0, 2}Output: GCDs of given ranges a
    14 min read
    Mean of range in array
    Given an array arr[] of n integers and q queries represented by an array queries[][], where queries[i][0] = l and queries[i][1] = r. For each query, the task is to calculate the mean of elements in the range l to r and return its floor value. Examples: Input: arr[] = [3, 7, 2, 8, 5] queries[][] = [[
    12 min read
    Difference Array | Range update query in O(1)
    You are given an integer array arr[] and a list of queries. Each query is represented as a list of integers where:[1, l, r, x]: Adds x to all elements from arr[l] to arr[r] (inclusive).[2]: Prints the current state of the array.You need to perform the queries in order.Examples : Input: arr[] = [10,
    10 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 <= L <= R <= 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 q
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences