Given an array A[ ] consisting of non-negative integers and a matrix Q[ ][ ] consisting of queries of the following two types:
- (1, l, val): Update A[l] to A[l] + val.
- (2, K): Find the lower_bound of K in the prefix sum array of A[ ]. If the lower_bound does not exist, print -1.
The task for each query of the second type is to print the index of the lower_bound of value K.
Examples:Â
Input: A[ ] = {1, 2, 3, 5, 8}, Q[ ][ ] = {{1, 0, 2}, {2, 5}, {1, 3, 5}}Â
Output: 1Â
Explanation:Â
Query 1: Update A[0] to A[0] + 2. Now A[ ] = {3, 2, 3, 5, 8}
Query 2: lower_bound of K = 5 in the prefix sum array {3, 5, 8, 13, 21} is 5 and index = 1.Â
Query 3: Update A[3] to A[3] + 5. Now A[ ] = {3, 2, 3, 10, 8}Input: A[ ] = {4, 1, 12, 8, 20}, Q[ ] = {{2, 50}, {1, 3, 12}, {2, 50}}Â
Output: -1Â Â
Naive approach:Â
The simplest approach is to first build a prefix sum array of a given array A[ ], and for queries of Type 1, update values and recalculate the prefix sum. For query of Type 2, perform a Binary Search on the prefix sum array to find the lower bound.
Time Complexity: O(Q*(N*logn))Â
Auxiliary Space: O(N)
Efficient Approach:Â
The above approach can be optimized Fenwick Tree. Using this Data Structure, the update queries in the prefix sum array can be performed in logarithmic time.Â
Follow the steps below to solve the problem:Â Â
- Construct the Prefix Sum Array using Fenwick Tree.
- For queries of Type 1, while l > 0, add val to A[l] traverse to the parent node by adding the least significant bit in l.
- For queries of Type 2, perform the Binary Search on the Fenwick Tree to obtain the lower bound.
- Whenever a prefix sum greater than K appears, store that index and traverse the left part of the Fenwick Tree. Otherwise, traverse the right part of the Fenwick Tree now, perform Binary Search.
- Finally, print the required index.
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 calculate and return// the sum of arr[0..index]int getSum(int BITree[], int index){Â Â Â Â int ans = 0;Â Â Â Â index += 1;Â
    // Traverse ancestors    // of BITree[index]    while (index > 0)    {                 // Update the sum of current        // element of BIT to ans        ans += BITree[index];Â
        // Update index to that        // of the parent node in        // getSum() view by        // subtracting LSB(Least        // Significant Bit)        index -= index & (-index);    }    return ans;}Â
// Function to update the Binary Index// Tree by replacing all ancestors of// index by their respective sum with valstatic void updateBIT(int BITree[], int n, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int index, int val){Â Â Â Â index = index + 1;Â
    // Traverse all ancestors    // and sum with 'val'.    while (index <= n)    {                 // Add 'val' to current        // node of BIT        BITree[index] += val;Â
        // Update index to that        // of the parent node in        // updateBit() view by        // adding LSB(Least        // Significant Bit)        index += index & (-index);    }}Â
// Function to construct the Binary// Indexed Tree for the given arrayint* constructBITree(int arr[], int n){         // Initialize the    // Binary Indexed Tree    int* BITree = new int[n + 1];Â
    for(int i = 0; i <= n; i++)        BITree[i] = 0;Â
    // Store the actual values in    // BITree[] using update()    for(int i = 0; i < n; i++)        updateBIT(BITree, n, i, arr[i]);Â
    return BITree;}Â
// Function to obtain and return// the index of lower_bound of kint getLowerBound(int BITree[], int arr[],                  int n, int k){    int lb = -1;    int l = 0, r = n - 1;Â
    while (l <= r)    {        int mid = l + (r - l) / 2;        if (getSum(BITree, mid) >= k)        {            r = mid - 1;            lb = mid;        }        else            l = mid + 1;    }    return lb;}Â
void performQueries(int A[], int n, int q[][3]){         // Store the Binary Indexed Tree    int* BITree = constructBITree(A, n);Â
    // Solve each query in Q    for(int i = 0;             i < sizeof(q[0]) / sizeof(int);             i++)    {        int id = q[i][0];Â
        if (id == 1)        {            int idx = q[i][1];            int val = q[i][2];            A[idx] += val;Â
            // Update the values of all            // ancestors of idx            updateBIT(BITree, n, idx, val);        }        else        {            int k = q[i][1];            int lb = getLowerBound(BITree,                                    A, n, k);            cout << lb << endl;        }    }}Â
// Driver Codeint main(){Â Â Â Â int A[] = { 1, 2, 3, 5, 8 };Â
    int n = sizeof(A) / sizeof(int);Â
    int q[][3] = { { 1, 0, 2 },                    { 2, 5, 0 },                    { 1, 3, 5 } };Â
    performQueries(A, n, q);}Â
// This code is contributed by jrishabh99 |
Java
// Java program to implement// the above approachimport java.util.*;import java.io.*;Â
class GFG {Â
    // Function to calculate and return    // the sum of arr[0..index]    static int getSum(int BITree[],                      int index)    {        int ans = 0;        index += 1;Â
        // Traverse ancestors        // of BITree[index]        while (index > 0) {Â
            // Update the sum of current            // element of BIT to ans            ans += BITree[index];Â
            // Update index to that            // of the parent node in            // getSum() view by            // subtracting LSB(Least            // Significant Bit)            index -= index & (-index);        }        return ans;    }Â
    // Function to update the Binary Index    // Tree by replacing all ancestors of    // index by their respective sum with val    static void updateBIT(int BITree[],                          int n, int index, int val)    {        index = index + 1;Â
        // Traverse all ancestors        // and sum with 'val'.        while (index <= n) {            // Add 'val' to current            // node of BIT            BITree[index] += val;Â
            // Update index to that            // of the parent node in            // updateBit() view by            // adding LSB(Least            // Significant Bit)            index += index & (-index);        }    }Â
    // Function to construct the Binary    // Indexed Tree for the given array    static int[] constructBITree(        int arr[], int n)    {        // Initialize the        // Binary Indexed Tree        int[] BITree = new int[n + 1];Â
        for (int i = 0; i <= n; i++)            BITree[i] = 0;Â
        // Store the actual values in        // BITree[] using update()        for (int i = 0; i < n; i++)            updateBIT(BITree, n, i, arr[i]);Â
        return BITree;    }Â
    // Function to obtain and return    // the index of lower_bound of k    static int getLowerBound(int BITree[],                             int[] arr, int n, int k)    {        int lb = -1;        int l = 0, r = n - 1;Â
        while (l <= r) {Â
            int mid = l + (r - l) / 2;            if (getSum(BITree, mid) >= k) {                r = mid - 1;                lb = mid;            }            else                l = mid + 1;        }        return lb;    }Â
    static void performQueries(int A[], int n, int q[][])    {Â
        // Store the Binary Indexed Tree        int[] BITree = constructBITree(A, n);Â
        // Solve each query in Q        for (int i = 0; i < q.length; i++) {            int id = q[i][0];Â
            if (id == 1) {                int idx = q[i][1];                int val = q[i][2];                A[idx] += val;Â
                // Update the values of all                // ancestors of idx                updateBIT(BITree, n, idx, val);            }            else {                int k = q[i][1];                int lb = getLowerBound(                    BITree, A, n, k);                System.out.println(lb);            }        }    }Â
    // Driver Code    public static void main(String[] args)    {        int A[] = { 1, 2, 3, 5, 8 };Â
        int n = A.length;Â
        int[][] q = { { 1, 0, 2 },                      { 2, 5 },                      { 1, 3, 5 } };Â
        performQueries(A, n, q);    }} |
Python3
# Python3 program to implement# the above approachÂ
# Function to calculate and return# the sum of arr[0..index]def getSum(BITree, index):Â
    ans = 0    index += 1Â
    # Traverse ancestors    # of BITree[index]    while (index > 0):Â
        # Update the sum of current        # element of BIT to ans        ans += BITree[index]Â
        # Update index to that        # of the parent node in        # getSum() view by        # subtracting LSB(Least        # Significant Bit)        index -= index & (-index)Â
    return ansÂ
# Function to update the # Binary Index Tree by # replacing all ancestors # of index by their respective # sum with valdef updateBIT(BITree, n,              index, val):       index = index + 1Â
    # Traverse all ancestors    # and sum with 'val'.    while (index <= n):Â
        # Add 'val' to current        # node of BIT        BITree[index] += valÂ
        # Update index to that        # of the parent node in        # updateBit() view by        # adding LSB(Least        # Significant Bit)        index += index & (-index)Â
# Function to construct the Binary# Indexed Tree for the given arraydef constructBITree(arr, n):Â
    # Initialize the    # Binary Indexed Tree    BITree = [0] * (n + 1)Â
    for i in range(n + 1):        BITree[i] = 0Â
    # Store the actual values in    # BITree[] using update()    for i in range(n):        updateBIT(BITree, n, i, arr[i])Â
    return BITreeÂ
# Function to obtain and return# the index of lower_bound of kdef getLowerBound(BITree, arr,                  n, k):       lb = -1    l = 0    r = n - 1Â
    while (l <= r):        mid = l + (r - l) // 2        if (getSum(BITree,                    mid) >= k):            r = mid - 1            lb = mid        else:            l = mid + 1Â
    return lbÂ
def performQueries(A, n, q):Â
    # Store the Binary Indexed Tree    BITree = constructBITree(A, n)Â
    # Solve each query in Q    for i in range(len(q)):        id = q[i][0]Â
        if (id == 1):            idx = q[i][1]            val = q[i][2]            A[idx] += valÂ
            # Update the values of all            # ancestors of idx            updateBIT(BITree, n,                       idx, val)        else:Â
            k = q[i][1]            lb = getLowerBound(BITree,                               A, n, k)            print(lb)Â
# Driver Codeif __name__ == "__main__":Â
    A = [1, 2, 3, 5, 8]    n = len(A)    q = [[1, 0, 2],         [2, 5, 0],         [1, 3, 5]]    performQueries(A, n, q)Â
# This code is contributed by Chitranayal |
C#
// C# program to implement// the above approachusing System;Â
class GFG{Â
// Function to calculate and return// the sum of arr[0..index]static int getSum(int []BITree,                  int index){    int ans = 0;    index += 1;Â
    // Traverse ancestors    // of BITree[index]    while (index > 0)    {                 // Update the sum of current        // element of BIT to ans        ans += BITree[index];Â
        // Update index to that        // of the parent node in        // getSum() view by        // subtracting LSB(Least        // Significant Bit)        index -= index & (-index);    }    return ans;}Â
// Function to update the Binary Index// Tree by replacing all ancestors of// index by their respective sum with valstatic void updateBIT(int []BITree,                      int n, int index,                      int val){    index = index + 1;Â
    // Traverse all ancestors    // and sum with 'val'.    while (index <= n)    {                 // Add 'val' to current        // node of BIT        BITree[index] += val;Â
        // Update index to that        // of the parent node in        // updateBit() view by        // adding LSB(Least        // Significant Bit)        index += index & (-index);    }}Â
// Function to construct the Binary// Indexed Tree for the given arraystatic int[] constructBITree(int []arr,                             int n){    // Initialize the    // Binary Indexed Tree    int[] BITree = new int[n + 1];Â
    for(int i = 0; i <= n; i++)        BITree[i] = 0;Â
    // Store the actual values in    // BITree[] using update()    for(int i = 0; i < n; i++)        updateBIT(BITree, n, i, arr[i]);Â
    return BITree;}Â
// Function to obtain and return// the index of lower_bound of kstatic int getLowerBound(int []BITree,                         int[] arr, int n,                          int k){    int lb = -1;    int l = 0, r = n - 1;Â
    while (l <= r)     {        int mid = l + (r - l) / 2;        if (getSum(BITree, mid) >= k)         {            r = mid - 1;            lb = mid;        }        else            l = mid + 1;    }    return lb;}Â
static void performQueries(int []A, int n,                           int [,]q){         // Store the Binary Indexed Tree    int[] BITree = constructBITree(A, n);Â
    // Solve each query in Q    for(int i = 0; i < q.GetLength(0); i++)    {        int id = q[i, 0];Â
        if (id == 1)         {            int idx = q[i, 1];            int val = q[i, 2];            A[idx] += val;Â
            // Update the values of all            // ancestors of idx            updateBIT(BITree, n, idx, val);        }        else        {            int k = q[i, 1];            int lb = getLowerBound(BITree,                                   A, n, k);            Console.WriteLine(lb);        }    }}Â
// Driver Codepublic static void Main(String[] args){Â Â Â Â int []A = { 1, 2, 3, 5, 8 };Â
    int n = A.Length;Â
    int [,]q = { { 1, 0, 2 },                 { 2, 5, 0 },                 { 1, 3, 5 } };Â
    performQueries(A, n, q);}}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>// Javascript program to implement// the above approachÂ
// Function to calculate and return// the sum of arr[0..index]function getSum(BITree, index) {Â Â Â Â let ans = 0;Â Â Â Â index += 1;Â
    // Traverse ancestors    // of BITree[index]    while (index > 0) {Â
        // Update the sum of current        // element of BIT to ans        ans += BITree[index];Â
        // Update index to that        // of the parent node in        // getSum() view by        // subtracting LSB(Least        // Significant Bit)        index -= index & (-index);    }    return ans;}Â
// Function to update the Binary Index// Tree by replacing all ancestors of// index by their respective sum with valfunction updateBIT(BITree, n, index, val) {Â Â Â Â index = index + 1;Â
    // Traverse all ancestors    // and sum with 'val'.    while (index <= n) {Â
        // Add 'val' to current        // node of BIT        BITree[index] += val;Â
        // Update index to that        // of the parent node in        // updateBit() view by        // adding LSB(Least        // Significant Bit)        index += index & (-index);    }}Â
// Function to construct the Binary// Indexed Tree for the given arrayfunction constructBITree(arr, n) {Â
    // Initialize the    // Binary Indexed Tree    let BITree = new Array(n + 1);Â
    for (let i = 0; i <= n; i++)        BITree[i] = 0;Â
    // Store the actual values in    // BITree[] using update()    for (let i = 0; i < n; i++)        updateBIT(BITree, n, i, arr[i]);Â
    return BITree;}Â
// Function to obtain and return// the index of lower_bound of kfunction getLowerBound(BITree, arr, n, k) {Â Â Â Â let lb = -1;Â Â Â Â let l = 0, r = n - 1;Â
    while (l <= r) {        let mid = Math.floor(l + (r - l) / 2);        if (getSum(BITree, mid) >= k) {            r = mid - 1;            lb = mid;        }        else            l = mid + 1;    }    return lb;}Â
function performQueries(A, n, q) {Â
    // Store the Binary Indexed Tree    let BITree = constructBITree(A, n);Â
    // Solve each query in Q    for (let i = 0;        i < q.length;        i++) {        let id = q[i][0];Â
        if (id == 1) {            let idx = q[i][1];            let val = q[i][2];            A[idx] += val;Â
            // Update the values of all            // ancestors of idx            updateBIT(BITree, n, idx, val);        }        else {            let k = q[i][1];            let lb = getLowerBound(BITree,                A, n, k);            document.write(lb + "<br>");        }    }}Â
// Driver CodeÂ
let A = [1, 2, 3, 5, 8];Â
let n = A.length;Â
let q = [[1, 0, 2],        [2, 5, 0],        [1, 3, 5]];Â
performQueries(A, n, q);Â
Â
// This code is contributed by gfgking</script> |
1
Â
Time Complexity: O(Q*(logN)2)Â
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Find More Information here on that Topic: geeksforgeeks.org/queries-to-find-the-lower-bound-of-k-from-prefix-sum-array-with-updates-using-fenwick-tree/ […]