AlgoMaster Logo

Range Sum Query - Mutable

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

  • Each update or sumRange query operates in constant time when using a brute force method.
  • On update operation, we simply change the value at the designated index.
  • On sumRange(i, j) operation, we iterate through the array from index i to j and calculate the sum.

This approach sacrifices performance for simplicity, offering an easy-to-understand solution at the cost of increased time complexity for range queries.

Code:

2. Segment Tree

Intuition:

  • A Segment Tree is designed specifically to solve range query problems efficiently.
  • It pre-computes the range sums and supports efficient update and range sum operations.
  • With Segment Trees, both update and sumRange operations can be conducted in O(log n) time, balancing between brute force direct access and high efficiency.

Code:

3. Binary Indexed Tree (Fenwick Tree)

Intuition:

  • A Binary Indexed Tree (or Fenwick Tree) is another advanced data structure that supports prefix sum operations efficiently, similar to Segment Trees.
  • Fenwick Trees provide a simpler, more compact structure that allows both updates and prefix sum retrievals in O(log n) time.

Code: