Modified Range Sum in a given Array without updates

Given an array arr[] of size N containing distinct numbers from 1 to N in any order, the task is to perform modified range sum in this array according to the following rules.
For each index ‘i‘ in array arr:

  • The starting index of the range ‘L‘ is selected as i + 1
  • The ending index of the range ‘R‘ is selected as:
    • min(arr[i], N-1); if arr[i] > i
    • max(i+1, arr[i]); if arr[i] < i+1
  • For updation, the values in range arr[L] to arr[R] is incremented by 1.
  • The range is found out using the input array and not the updated array

Examples:

Input: arr[] = {4, 1, 3, 2}
Output: 4 2 5 4
Explanation:
For i = 0 -> Element in input array = 4. Therefore L = 1, and R = min(4, N-1) = 3. Hence, all the elements from arr[1] to arr[3] are incremented by 1. The elements after update operation are {4, 2, 4, 3}.
For i = 1 -> Element in input array = 1. Therefore L = 2, and R = max(1, i+1) = 2. Hence, all the elements from arr[2] to arr[2] are incremented by 1. The elements after update operation are {4, 2, 5, 3}.
For i = 2 -> Element in input array = 3. Therefore L = 3, and R = min(3, N-1) = 3. Hence, all the elements from arr[3] to arr[3] are incremented by 1. The elements after update operation are {4, 2, 5, 4}.
For i = 3 -> The array is unaffected. Therefore the elements after update operation are {4, 2, 5, 4}.
The resulting array is {4, 2, 5, 4}.

Input: arr[] = {2, 1}
Output: {2, 2}
Explanation:
The first element is 2. So arr[1] gets incremented by 1. Hence, the resulting array is {2, 2}.

Naive Approach: The naive approach is to run a loop for each element and increase all the values from arr[i+1] to arr[min(i+arr[i], N-1)] by 1. The time complexity of this approach is O(N2).



Efficient Approach: This problem can be solved in O(N) by using an extra space of O(N). The idea is to use the concept of prefix sum array. The following steps are followed to compute the answer:

  • An array b[] of size N + 1 is declared and all the elements are initialized with 0.
  • For each element arr[i] in the given array, 1 is added to b[i+1] and subtracted from b[min(i + arr[i], N – 1)+ 1].
  • Then, prefix sum of the array b[] is calculated.
  • Finally, arr is updated as arr[i] = arr[i] + b[i].

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find elements in an array
// after performing range updates.
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to perform the update on the given
// input array arr[].
void update(vector<int>& arr,
            vector<int>& d, int n)
{
  
    // A new array of size N+1 is defined
    // and 1's are added in that array
    for (int i = 0; i < n - 1; i++) {
        d[i + 1] += 1;
        d[min(i + arr[i], n - 1) + 1] -= 1;
    }
  
    // Loop to perform the prefix sum
    // on the array d[].
    for (int i = 1; i < n; i++) {
        d[i] = d[i] + d[i - 1];
    }
}
  
// Function to print the final
// array after updation
void print(vector<int>& arr,
           vector<int>& d, int n)
{
  
    // Loop to add the values of d[i]
    // to arr[i]
    for (int i = 0; i < n; i++)
        cout << arr[i] + d[i] << " ";
}
  
// Function to perform modified range sum
void modifiedRangeSum(vector<int>& arr, int n)
{
  
    vector<int> d;
  
    // Loop to add N+1 0's in array d[]
    for (int i = 0; i <= n; i++)
        d.push_back(0);
  
    update(arr, d, n);
    print(arr, d, n);
}
  
// Driver code
int main()
{
    vector<int> arr = { 5, 4, 1, 3, 2 };
    int n = 5;
  
    modifiedRangeSum(arr, n);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find elements in an array
// after performing range updates.
import java.util.*;
  
class GFG{
  
static ArrayList<Integer> arr = new 
        ArrayList<Integer>(Arrays.asList(5, 4, 1, 3, 2));
static int n = 5;
  
// Function to perform the update on the given
// input array arr[].
static void update(ArrayList<Integer> d)
{
  
    // A new array of size N+1 is defined
    // and 1's are added in that array
    for (int i = 0; i < n - 1; i++) {
        d.set(i + 1,d.get(i+1)+1);
        int x = Math.min(i + arr.get(i), n - 1)+ 1;
        d.set(x,d.get(x)-1);
    }
  
    // Loop to perform the prefix sum
    // on the array d[].
    for (int i = 1; i < n; i++) {
        d.set(i,d.get(i)+d.get(i - 1));
    }
}
  
// Function to print the final
// array after updation
static void print(ArrayList<Integer> d)
{
  
    // Loop to add the values of d[i]
    // to arr[i]
    for (int i = 0; i < n; i++)
        System.out.print(arr.get(i) + d.get(i)+ " ");
}
  
// Function to perform modified range sum
static void modifiedRangeSum()
{
  
    ArrayList<Integer> d = new ArrayList<Integer>();
  
    // Loop to add N+1 0's in array d[]
    for (int i = 0; i <= n; i++)
        d.add(0);
  
    update(d);
    print(d);
}
  
// Driver code
public static void main(String args[])
{
    modifiedRangeSum();
}
}
  
// This code is contributed by Surendra_Gangwar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find elements in an array
# after performing range updates.
arr = []
d = [] 
  
# Function to perform the update on the given
# input array arr[].
def update( n):
      
    global d
    global arr
  
    # A new array of size N+1 is defined
    # and 1's are added in that array
    for i in range(n - 1): 
        d[i + 1] += 1
        d[min(i + arr[i], n - 1) + 1] -= 1
      
    # Loop to perform the prefix sum
    # on the array d[].
    for i in range(n):
        d[i + 1] = d[i + 1] + d[i ]
      
# Function to print the final
# array after updation
def print_( n):
      
    global d
    global arr
  
    # Loop to add the values of d[i]
    # to arr[i]
    for i in range(n):
        x = (arr[i] + d[i] )
        print(x, end = " ")
  
# Function to perform modified range sum
def modifiedRangeSum( n):
  
    global d
    global arr
  
    d = []
      
    # Loop to add N+1 0's in array d[]
    for i in range(n + 1):
        d.append(0)
  
    update( n)
    print_(n)
  
# Driver code
arr = [5, 4, 1, 3, 2
n = 5
  
modifiedRangeSum( n)
  
# This code is contributed by Arnab Kundu

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find elements in an array
// after performing range updates.
  
using System; 
        
class GFG { 
  
// Function to perform the update on the given
// input array arr[].
static void update(int []arr,int [] d, int n){
   
    // A new array of size N+1 is defined
    // and 1's are added in that array
    for (int i = 0; i < n - 1; i++) {
        d[i + 1] += 1;
        d[Math.Min(i + arr[i], n - 1) + 1] -= 1;
    }
   
    // Loop to perform the prefix sum
    // on the array d[].
    for (int i = 1; i < n; i++) {
        d[i] = d[i] + d[i - 1];
    }
}
   
// Function to print the final
// array after updation
static void print(int []arr,int []d, int n)
{
   
    // Loop to add the values of d[i]
    // to arr[i]
    for (int i = 0; i < n; i++)
        Console.Write((arr[i] + d[i])+" ");
}
   
// Function to perform modified range sum
static void modifiedRangeSum(int []arr, int n)
{
    int []d= new int[n+1];
   
    // Loop to add N+1 0's in array d[]
    for (int i = 0; i <= n; i++)
        d[i]=0;
   
    update(arr, d, n);
    print(arr, d, n);
}
  
// Driver code
public static void Main() 
  
    int [] arr = { 5, 4, 1, 3, 2 };
    int n = 5;
   
    modifiedRangeSum(arr, n);
  }
}  
  
// This code is contributed by mohit kumar 29

chevron_right


Output:

5 5 3 6 5

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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.