Open In App

Queries to update array elements in a range [L, R] to satisfy given conditions

Last Updated : 02 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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] = 2 – 1 + 1 modifies arr[] to { 0, 1, 2, 0 } 
Query2: Updating arr[0] = 0 – 0 + 1, arr[1] = 1 – 0 + 1 modifies arr[] to { 1, 3, 2, 0 } 
Therefore, the required output is 1 3 2 0.

Input: arr[] = { 0, 0, 0, 0 }, Q[][] = { { 1, 3 }, { 0, 1 } }
Output: 1 3 2 3

Naive Approach:The simplest approach to solve the problem is to traverse the array Q[][] and for each query, traverse all the array elements in the given range and update arr[i] += i – L + 1. Finally, print the array elements. 

Time Complexity: O(N * Q)
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized using the concept of Difference Array. Follow the steps below to solve the problem:

  • Initialize two arrays arr1[] and arr2[] and initialize all elements as 0.
  • Traverse the query array, Q[][]. For each query of type (L, R) update arr1[L] += 1, arr1[R + 1] -= 1 and arr2[R + 1] -= R – L + 1.
  • Traverse the array, arr1[] and store the prefix sum of arr1[], i.e. arr1[i] += arr1[i -1].
  • Traverse the array, arr2[] and update arr2[i] += arr2[i – 1] + arr1[i].
  • Finally, print the array, arr2[].

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the array
void printArray(int arr[], int N)
{
    for (int i = 0; i < N; i++) {
        cout << arr[i] << " ";
    }
}
 
// Function to perform the query in range [L, R]
// such that arr[i] += i - L + 1
void modifyArray(int arr[], int N, int Q[][2],
                 int cntQuery)
{
 
    // Initialize array
    int arr1[N + 1] = { 0 };
    int arr2[N + 1] = { 0 };
 
    // Traverse the query array
    for (int i = 0; i < cntQuery; i++) {
 
        // Stores range in 1-based index
        int L = Q[i][0] + 1, R = Q[i][1] + 1;
 
        // Update arr1[L]
        arr1[L]++;
 
        // Update arr1[R + 1]
        arr1[R + 1]--;
 
        // Update arr2[R + 1]
        arr2[R + 1] -= R - L + 1;
    }
 
    // Calculate prefix sum
    for (int i = 1; i <= N; i++)
        arr1[i] += arr1[i - 1];
 
    // Traverse the array, arr2[]
    for (int i = 1; i <= N; i++)
        arr2[i] += arr2[i - 1] + arr1[i];
 
    // Copy arr2[] into arr[]
    for (int i = 1; i <= N; i++)
        arr[i - 1] = arr2[i];
 
    printArray(arr, N);
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 0, 0, 0, 0 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    int Q[][2] = { { 1, 3 }, { 0, 1 } };
 
    // Stores count of query
    int cntQuery
        = sizeof(Q) / sizeof(Q[0]);
 
    // Function Call
    modifyArray(arr, N, Q, cntQuery);
 
    return 0;
}


Java




// Java program to implement
// the above approach
class GFG
{
 
    // Function to print the array
    static void printArray(int arr[], int N)
    {
        for (int i = 0; i < N; i++)
        {
            System.out.print(arr[i] + " ");
        }
    }
     
    // Function to perform the query in range [L, R]
    // such that arr[i] += i - L + 1
    static void modifyArray(int arr[], int N, int Q[][],
                     int cntQuery)
    {
     
        // Initialize array
        int arr1[] = new int[N + 2];
        int arr2[] = new int[N + 2];
     
        // Traverse the query array
        for (int i = 0; i < cntQuery; i++)
        {
     
            // Stores range in 1-based index
            int L = Q[i][0] + 1, R = Q[i][1] + 1;
     
            // Update arr1[L]
            arr1[L]++;
     
            // Update arr1[R + 1]
            arr1[R + 1]--;
     
            // Update arr2[R + 1]
            arr2[R + 1] -= R - L + 1;
        }
     
        // Calculate prefix sum
        for (int i = 1; i <= N; i++)
            arr1[i] += arr1[i - 1];
     
        // Traverse the array, arr2[]
        for (int i = 1; i <= N; i++)
            arr2[i] += arr2[i - 1] + arr1[i];
     
        // Copy arr2[] into arr[]
        for (int i = 1; i <= N; i++)
            arr[i - 1] = arr2[i];   
        printArray(arr, N);
    }
     
    // Driver Code
    public static void main (String[] args)
    {
       
        // Given array
        int arr[] = { 0, 0, 0, 0 };
     
        // Size of the array
        int N = arr.length;   
        int Q[][] = { { 1, 3 }, { 0, 1 } };
     
        // Stores count of query
        int cntQuery = Q.length;
     
        // Function Call
        modifyArray(arr, N, Q, cntQuery);
    }
}
 
// This code is contributed by AnkThon


Python3




# Python3 program to implement
# the above approach
 
# Function to print array
def printArray(arr, N):
    print(*arr)
 
# Function to perform the query in range [L, R]
# such that arr[i] += i - L + 1
def modifyArray(arr, N, Q, cntQuery):
 
    # Initialize array
    arr1 = [0 for i in range(N + 2)]
    arr2 = [0 for i in range(N + 2)]
 
    # Traverse the query array
    for i in range(cntQuery):
 
        # Stores range in 1-based index
        L = Q[i][0] + 1
        R = Q[i][1] + 1
        # print(L,R)
 
        # Update arr1[L]
        arr1[L] += 1
 
        # Update arr1[R + 1]
        arr1[R + 1] -= 1
 
        # Update arr2[R + 1]
        arr2[R + 1] -= R - L + 1
 
    # Calculate prefix sum
    for i in range(1, N + 1):
        arr1[i] += arr1[i - 1]
 
    # Traverse the array, arr2[]
    for i in range(1, N + 1):
        arr2[i] += arr2[i - 1] + arr1[i]
 
    # Copy arr2[] into arr[]
    for i in range(1, N + 1):
        arr[i - 1] = arr2[i]
    printArray(arr, N)
 
# Driver Code
if __name__ == '__main__':
     
    # Given array
    arr = [0, 0, 0, 0]
 
    # Size of the array
    N = len(arr)
    Q = [[ 1, 3 ], [ 0, 1 ]]
 
    # Stores count of query
    cntQuery = len(Q)
 
    # Function Call
    modifyArray(arr, N, Q, cntQuery)
 
# This code is contributed by mohit kumar 29.


C#




// C# program to implement
// the above approach
using System;
class GFG
{
 
    // Function to print the array
    static void printArray(int []arr, int N)
    {
        for (int i = 0; i < N; i++)
        {
            Console.Write(arr[i] + " ");
        }
    }
     
    // Function to perform the query in range [L, R]
    // such that arr[i] += i - L + 1
    static void modifyArray(int []arr, int N, int[,] Q,
                     int cntQuery)
    {
     
        // Initialize array
        int []arr1 = new int[N + 2];
        int []arr2 = new int[N + 2];
     
        // Traverse the query array
        for (int i = 0; i < cntQuery; i++)
        {
     
            // Stores range in 1-based index
            int L = Q[i,0] + 1, R = Q[i,1] + 1;
     
            // Update arr1[L]
            arr1[L]++;
     
            // Update arr1[R + 1]
            arr1[R + 1]--;
     
            // Update arr2[R + 1]
            arr2[R + 1] -= R - L + 1;
        }
     
        // Calculate prefix sum
        for (int i = 1; i <= N; i++)
            arr1[i] += arr1[i - 1];
     
        // Traverse the array, arr2[]
        for (int i = 1; i <= N; i++)
            arr2[i] += arr2[i - 1] + arr1[i];
     
        // Copy arr2[] into arr[]
        for (int i = 1; i <= N; i++)
            arr[i - 1] = arr2[i];   
        printArray(arr, N);
    }
     
    // Driver Code
    public static void Main()
    {
       
        // Given array
        int []arr = { 0, 0, 0, 0 };
     
        // Size of the array
        int N = arr.Length;   
        int [,]Q = { { 1, 3 }, { 0, 1 } };
     
        // Stores count of query
        int cntQuery = 2;
     
        // Function Call
        modifyArray(arr, N, Q, cntQuery);
    }
}
 
// This code is contributed by bgangwar59.


Javascript




<script>
 
// Javascript program to implement
// the above approach
 
// Function to print the array
function printArray(arr, N)
{
    for(let i = 0; i < N; i++)
    {
        document.write(arr[i] + " ");
    }
}
 
// Function to perform the query in
// range [L, R] such that
// arr[i] += i - L + 1
function modifyArray(arr, N, Q, cntQuery)
{
 
    // Initialize array
    let arr1 = new Array(N + 2).fill(0);
    let arr2 = new Array(N + 2).fill(0);
     
    // Traverse the query array
    for(let i = 0; i < cntQuery; i++)
    {
     
        // Stores range in 1-based index
        let L = Q[i][0] + 1, R = Q[i][1] + 1;
         
        // Update arr1[L]
        arr1[L]++;
         
        // Update arr1[R + 1]
        arr1[R + 1]--;
         
        // Update arr2[R + 1]
        arr2[R + 1] -= R - L + 1;
    }
     
    // Calculate prefix sum
    for(let i = 1; i <= N; i++)
        arr1[i] += arr1[i - 1];
     
    // Traverse the array, arr2[]
    for(let i = 1; i <= N; i++)
        arr2[i] += arr2[i - 1] + arr1[i];
     
    // Copy arr2[] into arr[]
    for(let i = 1; i <= N; i++)
        arr[i - 1] = arr2[i];  
         
    prletArray(arr, N);
}
 
// Driver Code
 
// Given array
let arr = [ 0, 0, 0, 0 ];
 
// Size of the array
let N = arr.length;  
let Q = [ [ 1, 3 ], [ 0, 1 ] ];
 
// Stores count of query
let cntQuery = Q.length;
 
// Function Call
modifyArray(arr, N, Q, cntQuery);
 
// This code is contributed by avijitmondal1998
 
</script>


Output: 

1 3 2 3

 

Time Complexity: O(N+Q)
Auxiliary Space: O(N)



Similar Reads

Count of numbers in the range [L, R] which satisfy the given conditions
Given a range [L, R], the task is to find the count of numbers from this range that satisfy the below conditions: All the digit in the number are distinct.All the digits are less than or equal to 5. Examples: Input: L = 4, R = 13 Output: 5 4, 5, 10, 12 and 13 are the only valid numbers in the range [4, 13].Input: L = 100, R = 1000 Output: 100 Appro
28 min read
Minimum number of substrings the given string can be splitted into that satisfy the given conditions
Given a string str and a string array arr[], the task is to find the minimum count of substrings this can be split into such that every substring is present in the given string array arr[]. Examples: Input: str = "111112", arr[] = {"11", "111", "11111", "2"}Output: 2 "11111" and "2" are the required substrings. "11", "111" and "2" can also be a val
13 min read
Count of triplets in an array that satisfy the given conditions
Given an array arr[] of N elements, the task is to find the count of triplets (arr[i], arr[j], arr[k]) such that (arr[i] + arr[j] + arr[k] = L) and (L % arr[i] = L % arr[j] = L % arr[k] = 0.Examples: Input: arr[] = {2, 4, 5, 6, 7} Output: 1 Only possible triplet is {2, 4, 6}Input: arr[] = {4, 4, 4, 4, 4} Output: 10 Approach: Consider the equations
13 min read
Minimum increment/decrement operations required on Array to satisfy given conditions
Given an array arr[] of size N, the task is to find the minimum number of increment or decrement operations required at any index i such that for each i (1 ? i &lt; N) if the sum of elements at index from 1 to i is positive then the sum of elements from 1 to i + 1 must be negative or vice versa. Note: Consider array as 1-based indexing. Examples: I
11 min read
Find maximum value of Indices of Array that satisfy the given conditions
Given an integer N (N ? 5) Then assume you have two infinite arrays X and Y where X[] is an array of element N and each element of Y[] is 2i where i is the index of the array, the task is to find two indices let's say A and B which are the maximum value of the index at which the prefix sum in X[] is at least the same as the prefix sum of Y[] and th
9 min read
Number of strings in two array satisfy the given conditions
Given two arrays of string arr1[] and arr2[]. For each string in arr2[](say str2), the task is to count numbers string in arr1[](say str1) which satisfy the below conditions: The first characters of str1 and str2 must be equal.String str2 must contain each character of string str1.Examples: Input: arr1[] = {"aaaa", "asas", "able", "ability", "actt"
14 min read
Find numbers a and b that satisfy the given conditions
Given an integer n, the task is to find two integers a and b which satisfy the below conditions: a % b = 0a * b &gt; na / b &lt; n If no pair satisfies the above conditions then print -1. Note: There can be multiple (a, b) pairs satisfying the above conditions for n.Examples: Input: n = 10 Output: a = 90, b = 10 90 % 10 = 0 90 * 10 = 900 &gt; 10 90
6 min read
Generate a string consisting of characters 'a' and 'b' that satisfy the given conditions
Given two integers A and B, the task is to generate and print a string str such that: str must only contain the characters 'a' and 'b'.str has length A + B and the occurrence of the character 'a' is equal to A and the occurrence of character 'b' is equal to BThe sub-strings "aaa" or "bbb" must not occur in str. Note: For the given values of A and B
6 min read
Count pairs of strings that satisfy the given conditions
Given an array arr[] of N strings consisting of lowercase characters, the task is to count the pairs in the array which satisfy the given conditions: Both strings have an equal number of pairs.The first vowels of both the strings are same.The last vowel of both strings is the same. Note that a string can only be used in a single pair. Examples: Inp
6 min read
Count of N digit numbers possible which satisfy the given conditions
Given an integer N, the Task is to find the total number of N digit numbers possible such that: All the digits of the numbers are from the range [0, N].There are no leading 0s.All the digits in a number are distinct. Examples: Input: N = 2 Output: 4 10, 12, 20 and 21 are the only possible 2 digit numbers which satisfy the given conditions.Input: N
4 min read