Range queries for alternatively addition and subtraction on given Array

Given an array arr[] of N integers and Q queries where every row consists of two numbers L and R which denotes the range [L, R], the task is to find the value of alternate addition and subtraction of the array element between range [L, R].
Examples:Â
Input: arr[] = {10, 13, 15, 2, 45, 31, 22, 3, 27}, Q[][] = {{2, 5}, {6, 8}, {1, 7}, {4, 8}, {0, 5}}Â
Output: 27 46 -33 60 24Â
Explanation:Â
Result of query {2, 5} is 27 ( 15 – 2 + 45 – 31)Â
Result of query {6, 8} is 46 ( 22 – 3 + 27)Â
Result of query {1, 7} is -33 ( 13 – 15 + 2 – 45 + 31 – 22 + 3)Â
Result of query {4, 8} is 60 ( 45 – 31 + 22 – 3 + 27)Â
Result of query {0, 5} is 24 ( 10 – 13 + 15 – 2 + 45 – 31)Input: arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1}, Q[] = {{2, 5}, {6, 8}, {1, 7}, {4, 8}, {0, 5}}Â
Output: 0 1 1 1 0Â
Naive Approach: The naive idea is to iterate from index L to R for each query and find the value of alternatively adding and subtracting the elements of the array and print the value after the operations are performed.
Below is the implementation of the above approach:Â Â
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Structure to represent a range querystruct Query {Â Â Â Â int L, R;};Â
// Function to find the result of// alternatively adding and subtracting// elements in the range [L, R]int findResultUtil(int arr[],                   int L, int R){    int result = 0;Â
    // A boolean variable flag to    // alternatively add and subtract    bool flag = false;Â
    // Iterate from [L, R]    for (int i = L; i <= R; i++) {Â
        // if flag is false, then        // add & toggle the flag        if (flag == false) {            result = result + arr[i];            flag = true;        }Â
        // if flag is true subtract        // and toggle the flag        else {            result = result - arr[i];            flag = false;        }    }Â
    // Return the final result    return result;}Â
// Function to find the value// for each queryvoid findResult(int arr[], int n,                Query q[], int m){Â
    // Iterate for each query    for (int i = 0; i < m; i++) {        cout << findResultUtil(arr,                               q[i].L,                               q[i].R)             << " ";    }}Â
// Driver Codeint main(){Â
    // Given array    int arr[] = { 10, 13, 15, 2, 45,                  31, 22, 3, 27 };Â
    int n = sizeof(arr) / sizeof(arr[0]);Â
    // Given Queries    Query q[] = { { 2, 5 }, { 6, 8 },                   { 1, 7 }, { 4, 8 },                   { 0, 5 } };Â
    int m = sizeof(q) / sizeof(q[0]);Â
    // Function Call    findResult(arr, n, q, m);    return 0;} |
Java
// Java program for the above approachimport java.util.*;Â
class GFG{Â
// Structure to represent a range querystatic class Query{Â Â Â Â int L, R;Â Â Â Â public Query(int l, int r)Â Â Â Â {Â Â Â Â Â Â Â Â super();Â Â Â Â Â Â Â Â L = l;Â Â Â Â Â Â Â Â R = r;Â Â Â Â }};Â
// Function to find the result of// alternatively adding and subtracting// elements in the range [L, R]static int findResultUtil(int arr[],                          int L, int R){    int result = 0;Â
    // A boolean variable flag to    // alternatively add and subtract    boolean flag = false;Â
    // Iterate from [L, R]    for(int i = L; i <= R; i++)    {                 // If flag is false, then        // add & toggle the flag        if (flag == false)         {            result = result + arr[i];            flag = true;        }Â
        // If flag is true subtract        // and toggle the flag        else        {            result = result - arr[i];            flag = false;        }    }Â
    // Return the final result    return result;}Â
// Function to find the value// for each querystatic void findResult(int arr[], int n,                       Query q[], int m){Â
    // Iterate for each query    for(int i = 0; i < m; i++)    {        System.out.print(findResultUtil(arr,              q[i].L, q[i].R) + " ");    }}Â
// Driver Codepublic static void main(String[] args){Â
    // Given array    int arr[] = { 10, 13, 15, 2, 45,                  31, 22, 3, 27 };Â
    int n = arr.length;Â
    // Given Queries    Query q[] = { new Query(2, 5), new Query(6, 8),                   new Query(1, 7), new Query(4, 8),                   new Query(0, 5) };Â
    int m = q.length;Â
    // Function call    findResult(arr, n, q, m);}}Â
// This code is contributed by Princi Singh |
Python3
# Python3 program for the above approachÂ
# Function to find the result of# alternatively adding and subtracting# elements in the range [L, R]def findResultUtil(arr, L, R):Â Â Â Â Â Â Â Â Â result = 0Â
    # A boolean variable flag to    # alternatively add and subtract    flag = FalseÂ
    # Iterate from [L, R]    for i in range(L, R + 1):                 # If flag is False, then        # add & toggle the flag        if (flag == False):            result = result + arr[i]            flag = TrueÂ
        # If flag is True subtract        # and toggle the flag        else:            result = result - arr[i]            flag = FalseÂ
    # Return the final result    return resultÂ
# Function to find the value# for each querydef findResult(arr, n, q, m):Â
    # Iterate for each query    for i in range(m):        print(findResultUtil(arr,                              q[i][0],                              q[i][1]),                             end = " ")Â
# Driver Codeif __name__ == '__main__':Â
    # Given array    arr = [ 10, 13, 15, 2, 45,            31, 22, 3, 27 ]Â
    n = len(arr)Â
    # Given Queries    q = [ [ 2, 5 ], [ 6, 8 ],           [ 1, 7 ], [ 4, 8 ],           [ 0, 5 ] ]Â
    m = len(q)Â
    # Function Call    findResult(arr, n, q, m)Â
# This code is contributed by mohit kumar 29 |
C#
// C# program for the above approachusing System;class GFG{Â
// Structure to represent a range queryclass Query{Â Â Â Â public int L, R;Â Â Â Â public Query(int l, int r)Â Â Â Â {Â Â Â Â Â Â Â Â L = l;Â Â Â Â Â Â Â Â R = r;Â Â Â Â }};Â
// Function to find the result of// alternatively adding and subtracting// elements in the range [L, R]static int findResultUtil(int []arr,                          int L, int R){    int result = 0;Â
    // A bool variable flag to    // alternatively add and subtract    bool flag = false;Â
    // Iterate from [L, R]    for(int i = L; i <= R; i++)    {                 // If flag is false, then        // add & toggle the flag        if (flag == false)         {            result = result + arr[i];            flag = true;        }Â
        // If flag is true subtract        // and toggle the flag        else        {            result = result - arr[i];            flag = false;        }    }Â
    // Return the readonly result    return result;}Â
// Function to find the value// for each querystatic void findResult(int []arr, int n,                       Query []q, int m){Â
    // Iterate for each query    for(int i = 0; i < m; i++)    {        Console.Write(findResultUtil(arr,              q[i].L, q[i].R) + " ");    }}Â
// Driver Codepublic static void Main(String[] args){Â
    // Given array    int []arr = { 10, 13, 15, 2, 45,                  31, 22, 3, 27 };Â
    int n = arr.Length;Â
    // Given Queries    Query []q = { new Query(2, 5), new Query(6, 8),                   new Query(1, 7), new Query(4, 8),                   new Query(0, 5) };Â
    int m = q.Length;Â
    // Function call    findResult(arr, n, q, m);}}Â
// This code is contributed by gauravrajput1 |
Javascript
<script>Â
// Javascript program for the above approachÂ
// Function to find the result of// alternatively adding and subtracting// elements in the range [L, R]function findResultUtil(arr, L, R){Â Â Â Â var result = 0;Â
    // A boolean variable flag to    // alternatively add and subtract    var flag = false;Â
    // Iterate from [L, R]    for (var i = L; i <= R; i++) {Â
        // if flag is false, then        // add & toggle the flag        if (flag == false) {            result = result + arr[i];            flag = true;        }Â
        // if flag is true subtract        // and toggle the flag        else {            result = result - arr[i];            flag = false;        }    }Â
    // Return the final result    return result;}Â
// Function to find the value// for each queryfunction findResult(arr, n, q, m){Â
    // Iterate for each query    for (var i = 0; i < m; i++) {        document.write( findResultUtil(arr,                               q[i][0],                               q[i][1])             + " ");    }}Â
// Driver Code// Given arrayvar arr = [10, 13, 15, 2, 45,              31, 22, 3, 27 ];var n = arr.length;// Given Queriesvar q = [ [ 2, 5 ], [ 6, 8 ],               [ 1, 7 ], [ 4, 8 ],               [ 0, 5 ] ];var m = q.length;// Function CallfindResult(arr, n, q, m);Â
Â
</script> |
27 46 -33 60 24
Â
Time Complexity: O(N*Q)Â
Auxiliary Space: O(1)
Efficient Approach: The efficient approach is to use Prefix Sum Array to solve the above problem. Below are the steps:Â
- Initialize the first element of prefix array(say pre[]) to first element of the arr[].
- Traverse through an index from 1 to N-1 and alternative add and subtract the elements of arr[i] from pre[i-1] and store it in pre[i] to make a prefix array.
- Now, Iterate through each query from 1 to Q, and find the result on the basis of the below cases:Â
- Case 1: If L is zero then result is pre[R].
- Case 2: If L is non-zero, find the result using the equation:
result = Query(L, R) = pre[R] – pre[L - 1]
- If L is odd multiply the above result by -1.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; Â
// Structure to represent a query struct Query { Â Â Â Â int L, R; }; Â
// This function fills the Prefix Array void fillPrefixArray(int arr[], int n,                     int prefixArray[]) {     // Initialise the prefix array     prefixArray[0] = arr[0]; Â
    // Iterate all the element of arr[]     // and update the prefix array     for (int i = 1; i < n; i++) { Â
        // If n is even then, add the         // previous value of prefix array         // with the current value of arr         if (i % 2 == 0) { Â
            prefixArray[i]                 = prefixArray[i - 1]                 + arr[i];         } Â
        // if n is odd, then subtract         // the previous value of prefix         // Array from current value         else {             prefixArray[i]                 = prefixArray[i - 1]                 - arr[i];         }     } } Â
// Function to find the result of // alternatively adding and subtracting // elements in the range [L< R] int findResultUtil(int prefixArray[], Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int L, int R) { Â Â Â Â int result; Â
    // Case 1 : when L is zero     if (L == 0) {         result = prefixArray[R];     } Â
    // Case 2 : When L is non zero     else {         result = prefixArray[R]                 - prefixArray[L - 1];     } Â
    // If L is odd means range starts from     // odd position multiply result by -1     if (L & 1) {         result = result * (-1);     } Â
    // Return the final result     return result; } Â
// Function to find the sum of all // alternative add and subtract // between ranges [L, R] void findResult(int arr[], int n, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Query q[], int m) { Â
    // Declare prefix array     int prefixArray[n]; Â
    // Function Call to fill prefix arr[]     fillPrefixArray(arr, n, prefixArray); Â
    // Iterate for each query     for (int i = 0; i < m; i++) { Â
        cout << findResultUtil(prefixArray,                             q[i].L,                             q[i].R)             << " ";     } } Â
// Driver Code int main() { Â
    // Given array     int arr[] = { 10, 13, 15, 2, 45,                 31, 22, 3, 27 }; Â
    int n = sizeof(arr) / sizeof(arr[0]); Â
    // Given Queries     Query q[] = { { 2, 5 }, { 6, 8 },                 { 1, 7 }, { 4, 8 },                 { 0, 5 } }; Â
    int m = sizeof(q) / sizeof(q[0]); Â
    // Function Call     findResult(arr, n, q, m);     return 0; } |
Java
// Java program for the above approach import java.util.*;class GFG{ Â
// Structure to represent a query static class Query{ Â Â Â Â int L, R;Â
    public Query(int l, int r)     {        super();        L = l;        R = r;    } }; Â
// This function fills the Prefix Array static void fillPrefixArray(int arr[], int n,                             int prefixArray[]) {     // Initialise the prefix array     prefixArray[0] = arr[0]; Â
    // Iterate all the element of arr[]     // and update the prefix array     for (int i = 1; i < n; i++)     { Â
        // If n is even then, add the         // previous value of prefix array         // with the current value of arr         if (i % 2 == 0)        {             prefixArray[i] = prefixArray[i - 1] +                                            arr[i];         } Â
        // if n is odd, then subtract         // the previous value of prefix         // Array from current value         else        {             prefixArray[i] = prefixArray[i - 1] -                                            arr[i];         }     } } Â
// Function to find the result of // alternatively adding and subtracting // elements in the range [L< R] static int findResultUtil(int prefixArray[], Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int L, int R) { Â Â Â Â int result; Â
    // Case 1 : when L is zero     if (L == 0)     {         result = prefixArray[R];     } Â
    // Case 2 : When L is non zero     else    {         result = prefixArray[R] -                    prefixArray[L - 1];     } Â
    // If L is odd means range starts from     // odd position multiply result by -1     if (L % 2 == 1)     {         result = result * (-1);     } Â
    // Return the final result     return result; } Â
// Function to find the sum of all // alternative add and subtract // between ranges [L, R] static void findResult(int arr[], int n, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Query q[], int m) { Â
    // Declare prefix array     int []prefixArray = new int[n]; Â
    // Function Call to fill prefix arr[]     fillPrefixArray(arr, n, prefixArray); Â
    // Iterate for each query     for (int i = 0; i < m; i++)     {         System.out.print(findResultUtil(                           prefixArray, q[i].L,                                         q[i].R) + " ");     } } Â
// Driver Code public static void main(String[] args) { Â
    // Given array     int arr[] = { 10, 13, 15, 2, 45,                 31, 22, 3, 27 }; Â
    int n = arr.length; Â
    // Given Queries     Query q[] = {new Query( 2, 5 ), new Query( 6, 8 ),                  new Query( 1, 7 ), new Query( 4, 8 ),                  new Query( 0, 5 )}; Â
    int m = q.length; Â
    // Function Call     findResult(arr, n, q, m); } } Â
// This code is contributed by PrinciRaj1992 |
Python3
# Python program for the above approachÂ
# Structure to represent a queryclass Query:    def __init__(self,l,r):        self.L = l        self.R = rÂ
# This function fills the Prefix Arraydef fillPrefixArray(arr, n, prefixArray):         # Initialise the prefix array    prefixArray[0] = arr[0]Â
    # Iterate all the element of arr[]    # and update the prefix array    for i in range(1,n):                 # If n is even then, add the        # previous value of prefix array        # with the current value of arr        if (i % 2 == 0):            prefixArray[i] = prefixArray[i - 1] + arr[i]Â
        # if n is odd, then subtract        # the previous value of prefix        # Array from current value        else:            prefixArray[i] = prefixArray[i - 1] - arr[i]Â
# Function to find the result of# alternatively adding and subtracting# elements in the range [L< R]def findResultUtil(prefixArray, L, R):Â
    # Case 1 : when L is zero    if (L == 0):        result = prefixArray[R]Â
    # Case 2 : When L is non zero    else:        result = prefixArray[R] - prefixArray[L - 1]Â
    # If L is odd means range starts from    # odd position multiply result by -1    if (L % 2 == 1):        result = result * (-1)Â
    # Return the final result    return resultÂ
# Function to find the sum of all# alternative add and subtract# between ranges [L, R]def findResult(arr, n, q, m):         # Declare prefix array    prefixArray = [0 for i in range(n)]Â
    # Function Call to fill prefix arr[]    fillPrefixArray(arr, n, prefixArray)         # Iterate for each query    for i in range(m):        print(findResultUtil(prefixArray, q[i].L,q[i].R),end = " ")Â
# Driver CodeÂ
# Given arrayarr = [ 10, 13, 15, 2, 45, 31, 22, 3, 27 ]n = len(arr)Â
# Given Queriesq = [ Query(2, 5), Query(6, 8), Query(1, 7), Query(4, 8), Query(0, 5)]m = len(q)Â
# Function CallfindResult(arr, n, q, m)Â
# This code is contributed by shinjanpatra |
C#
// C# program for the above approach using System;class GFG{ Â
// Structure to represent a query class Query{    public int L, R;Â
    public Query(int l, int r)     {        L = l;        R = r;    } }; Â
// This function fills the Prefix Array static void fillPrefixArray(int []arr, int n,                             int []prefixArray) {     // Initialise the prefix array     prefixArray[0] = arr[0]; Â
    // Iterate all the element of []arr     // and update the prefix array     for (int i = 1; i < n; i++)     { Â
        // If n is even then, add the         // previous value of prefix array         // with the current value of arr         if (i % 2 == 0)        {             prefixArray[i] = prefixArray[i - 1] +                                          arr[i];         } Â
        // if n is odd, then subtract         // the previous value of prefix         // Array from current value         else        {             prefixArray[i] = prefixArray[i - 1] -                                          arr[i];         }     } } Â
// Function to find the result of // alternatively adding and subtracting // elements in the range [L< R] static int findResultUtil(int []prefixArray, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int L, int R) { Â Â Â Â int result; Â
    // Case 1 : when L is zero     if (L == 0)     {         result = prefixArray[R];     } Â
    // Case 2 : When L is non zero     else    {         result = prefixArray[R] -                  prefixArray[L - 1];     } Â
    // If L is odd means range starts from     // odd position multiply result by -1     if (L % 2 == 1)     {         result = result * (-1);     } Â
    // Return the readonly result     return result; } Â
// Function to find the sum of all // alternative add and subtract // between ranges [L, R] static void findResult(int []arr, int n, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Query []q, int m) { Â
    // Declare prefix array     int []prefixArray = new int[n]; Â
    // Function Call to fill prefix []arr     fillPrefixArray(arr, n, prefixArray); Â
    // Iterate for each query     for (int i = 0; i < m; i++)     {         Console.Write(findResultUtil(                           prefixArray, q[i].L,                                         q[i].R) + " ");     } } Â
// Driver Code public static void Main(String[] args) { Â
    // Given array     int []arr = { 10, 13, 15, 2, 45,                 31, 22, 3, 27 }; Â
    int n = arr.Length; Â
    // Given Queries     Query []q = {new Query( 2, 5 ), new Query( 6, 8 ),                  new Query( 1, 7 ), new Query( 4, 8 ),                  new Query( 0, 5 )}; Â
    int m = q.Length; Â
    // Function Call     findResult(arr, n, q, m); } } Â
// This code is contributed by Rohit_ranjan |
Javascript
<script>Â
// Javascript program for the above approachÂ
// Structure to represent a queryclass Query{Â Â Â Â constructor(l, r)Â Â Â Â {Â Â Â Â Â Â Â Â this.L = l;Â Â Â Â Â Â Â Â this.R = r;Â Â Â Â }}Â
// This function fills the Prefix Arrayfunction fillPrefixArray(arr, n, prefixArray){         // Initialise the prefix array    prefixArray[0] = arr[0];      // Iterate all the element of arr[]    // and update the prefix array    for(let i = 1; i < n; i++)    {                 // If n is even then, add the        // previous value of prefix array        // with the current value of arr        if (i % 2 == 0)        {            prefixArray[i] = prefixArray[i - 1] +                                           arr[i];        }          // if n is odd, then subtract        // the previous value of prefix        // Array from current value        else        {            prefixArray[i] = prefixArray[i - 1] -                                     arr[i];        }    }}Â
// Function to find the result of// alternatively adding and subtracting// elements in the range [L< R]function findResultUtil(prefixArray, L, R){     let result;      // Case 1 : when L is zero    if (L == 0)    {        result = prefixArray[R];    }      // Case 2 : When L is non zero    else    {        result = prefixArray[R] -                 prefixArray[L - 1];    }      // If L is odd means range starts from    // odd position multiply result by -1    if (L % 2 == 1)    {        result = result * (-1);    }      // Return the final result    return result;}Â
// Function to find the sum of all// alternative add and subtract// between ranges [L, R]function findResult(arr, n, q, m){         // Declare prefix array    let prefixArray = new Array(n);      // Function Call to fill prefix arr[]    fillPrefixArray(arr, n, prefixArray);      // Iterate for each query    for(let i = 0; i < m; i++)    {        document.write(findResultUtil(                        prefixArray, q[i].L,                                     q[i].R) + " ");    }}Â
// Driver CodeÂ
// Given arraylet arr = [ 10, 13, 15, 2, 45,            31, 22, 3, 27 ];let n = arr.length;Â
// Given Querieslet q = [ new Query(2, 5), new Query(6, 8),          new Query(1, 7), new Query(4, 8),          new Query(0, 5)];let m = q.length;Â
// Function CallfindResult(arr, n, q, m);Â
// This code is contributed by unknown2108Â
</script> |
Output:Â Â
27 46 -33 60 24
Time Complexity:O(N + Q)Â
Auxiliary Space: O(N)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



