713978. Update Queries

Medium

Update Queries

Summary

The Update Queries problem involves updating an array based on a series of queries. Each query consists of an index and a value, where the goal is to update the value at that index in the array. The problem requires efficient algorithms for both querying and updating the array.

Detailed Explanation

The given array can be viewed as a simple dynamic array, where we need to perform various operations like insertion, deletion, and modification of elements. We will use an array-based approach to solve this problem efficiently.

To implement this problem, you can use a data structure called a "Bit Vector" or a "Binary Indexed Tree (BIT)". This is particularly useful when the number of queries is large in comparison with the size of the array. Here's how it works:

  1. Initialize an empty BIT.
  2. Iterate over each query and update the BIT accordingly:
    • If the query is to increment a value at index i, you can do this by adding val to the BIT at position i. This can be done in O(log n) time complexity where n is the size of the array.
  3. To find the sum of all values up to an index i, you can query the BIT at position i. This also takes O(log n) time complexity.

This approach provides a more efficient solution compared to using arrays and nested loops for each query.

Time Complexity: The time complexity is O(q log n), where q is the number of queries and n is the size of the array. Space Complexity: The space complexity is O(n).

Optimized Solutions

Java

View on GeeksforGeeks
class UpdateQueries {
    int[] BIT;

    public void update(int index, int val) {
        while (index < BIT.length) {
            BIT[index] += val;
            index |= index + 1;
        }
    }

    public int query(int index) {
        int sum = 0;
        while (index >= 0) {
            sum += BIT[index];
            index &= index - 1;
        }
        return sum;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.