Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmModified Range Sum in a given Array without updates

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 a 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++




// 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;
}


Java




// 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


Python3




# 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


C#




// 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


Javascript




<script>
  
// Javascript program to find elements in an array
// after performing range updates.
  
// Function to perform the update on the given
// input array arr[].
function update(arr, d, n)
{
  
    // A new array of size N+1 is defined
    // and 1's are added in that array
    for (var 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 (var i = 1; i < n; i++) {
        d[i] = d[i] + d[i - 1];
    }
}
  
// Function to print the final
// array after updation
function print(arr, d, n)
{
  
    // Loop to add the values of d[i]
    // to arr[i]
    for (var i = 0; i < n; i++)
        document.write( arr[i] + d[i] + " ");
}
  
// Function to perform modified range sum
function modifiedRangeSum(arr, n)
{
  
    var d = [];
  
    // Loop to add N+1 0's in array d[]
    for (var i = 0; i <= n; i++)
        d.push(0);
  
    update(arr, d, n);
    print(arr, d, n);
}
  
// Driver code
var arr = [5, 4, 1, 3, 2];
var n = 5;
modifiedRangeSum(arr, n);
  
// This code is contributed by importantly.
</script>


Output: 

5 5 3 6 5

 

Time Complexity: O(n)
Auxiliary Space: O(n), where n is the size of the given vector.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Calisto Chipfumbu
Calisto Chipfumbuhttp://cchipfumbu@gmail.com
I have 5 years' worth of experience in the IT industry, primarily focused on Linux and Database administration. In those years, apart from learning significant technical knowledge, I also became comfortable working in a professional team and adapting to my environment, as I switched through 3 roles in that time.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments