Skip to main content
Back to problems
Leetcode
Medium
Arrays
Segment Trees
Fenwick Trees
Google
Range Sum Query Mutable

Design a data structure that supports point updates and range-sum queries on an array.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.

Mutable Range Sum Query

gfg
Problem Statement

Problem

You are given an integer array that changes over time. Build a data structure that can:

  1. Update the value at a single index.
  2. Query the sum of values within any inclusive subarray range.

After each update, future queries must reflect the new values.

Your goal is to support both operations efficiently, rather than recomputing sums from scratch each time.

Input Format

  • An initial integer array nums.
  • A sequence of operations of two types:
    • update(index, val): set nums[index] = val
    • sumRange(left, right): return the sum of nums[left..right] inclusive

Output Format

  • For each range-sum query, return the computed sum as an integer.

Constraints

  • The array length and number of operations can be large enough that naive re-summing after every update is too slow.
  • Indices are zero-based.
  • Range queries are inclusive.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1, 3, 5]
update(1, 2)
sumRange(0, 2)
sumRange(1, 2)

Output

[8, 7]

Explanation

After the update, the array becomes [1, 2, 5]. The sum of the full range is 8, and the sum of the last two elements is 7.

Example 2

Input

nums = [0, -1, 4, 2]
sumRange(1, 3)
update(2, 10)
sumRange(0, 2)

Output

[5, 9]

Explanation

The first query returns -1 + 4 + 2 = 5. After updating index 2, the array becomes [0, -1, 10, 2], so the second query returns 0 + (-1) + 10 = 9.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.