Constant time range add operation on an array
Last Updated :
19 Sep, 2023
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.
Implementation:
C++
// 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 array
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
void printArr(int arr[], int N)
{
updateArray(arr, N);
for (int i = 0; i < N; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver code
int 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
// Java program to get updated array after
// many array range add operation
import 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
# 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 code
N = 6
arr = [0 for i in range(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 Anant Agarwal.
C#
// C# program to get updated array after
// many array range add operation
using 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
// 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 array
function 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 array
function 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 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 ita_c
?>
JavaScript
<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>
Output100 200 300 200 100 100
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Binary array after M range toggle operations
Consider a binary array consisting of N elements (initially all elements are 0). After that, you are given M commands where each command is of form a b, which means you have to toggle all the elements of the array in range a to b (both inclusive). After the execution of all M commands, you have to f
6 min read
Range and Coefficient of range of Array
Given an array arr of integer elements, the task is to find the range and coefficient of range of the given array where: Range: Difference between the maximum value and the minimum value in the distribution. Coefficient of Range: (Max â Min) / (Max + Min). Examples: Input: arr[] = {15, 16, 10, 9, 6,
7 min read
Count number of triplets in an array having sum in the range [a, b]
Given an array of distinct integers and a range [a, b], the task is to count the number of triplets having a sum in the range [a, b].Examples: Input : arr[] = {8, 3, 5, 2} range = [7, 11] Output : 1 There is only one triplet {2, 3, 5} having sum 10 in range [7, 11]. Input : arr[] = {2, 7, 5, 3, 8, 4
15+ min read
Compress the array into Ranges
Given an array of integers of size N, The task is to print the consecutive integers as a range. Examples: Input : N = 7, arr=[7, 8, 9, 15, 16, 20, 25] Output : 7-9 15-16 20 25 Consecutive elements present are[ {7, 8, 9}, {15, 16}, {20}, {25} ] Hence output the result as 7-9 15-16 20 25 Input : N = 6
6 min read
Missing Elements of a Range in an Array
Given an array of size N. Let min and max be the minimum and maximum in the array respectively. Task is to find how many number should be added to the given array such that all the element in the range [min, max] occur at-least once in the array.Examples: Input : arr[] = {4, 5, 3, 8, 6}Output : 1Onl
7 min read
Concatenate given array twice
Given an array arr[] of N elements, the task is to concatenate it twice, i.e. create an array of size 2*N by appending the copy of the given array to itself. Example: Input: arr[] = {1, 2, 1}Output: 1 2 1 1 2 1Explanation: The given array arr[] = {1, 2, 1}, can be appended to itself resulting in arr
4 min read
Print modified array after executing the commands of addition and subtraction
Given an array of size 'n' and a given set of commands of size 'm'. Every command consist of four integers q, l, r, k. These commands are of following types: If q = 0, add 'k' to all integers in range 'a' to 'b'(1 <= a <= b <= n). If q = 1, subtract 'k' to all integers in range 'a' to 'b'(1
8 min read
Range product queries in an array
We have an array of integers and a set of range queries. For every query, we need to find product of elements in the given range. Example: Input : arr[] = {5, 10, 15, 20, 25} queries[] = {(3, 5), (2, 2), (2, 3)} Output : 7500, 10, 150 7500 = 15 x 20 x 25 10 = 10 150 = 10 x 15 A naive approach would
10 min read
Minimum cost to equal all elements of array using two operation
Given an array arr[] of n positive integers. There are two operations allowed: Operation 1 : Pick any two indexes, increase value at one index by 1 and decrease value at another index by 1. It will cost a. Operation 2 : Pick any index and increase its value by 1. It will cost b. The task is to find
8 min read
Print modified array after multiple array range increment operations
Given an array containing n integers and a value d. m queries are given. Each query has two values start and end. For each query, the problem is to increment the values from the start to end index in the given array by the given value d. A linear time-efficient solution is required for handling such
10 min read