WorkspaceProblem lab
ALGORITHM VISUALIZER

Range Sum Queries

Opening the interactive workspace…

Understanding Range Sum Queries

For each inclusive range [left, right], return the sum of nums[left] through nums[right]. Return one answer per query in the same order.

How it works

A prefix array with a leading zero removes the special case for ranges beginning at index zero.

Build prefix[i + 1] = prefix[i] + nums[i]. Answer each query as prefix[right + 1] − prefix[left].

Try an example

Input: nums = [-2, 0, 3, -5, 2, -1], queries = [[0, 2], [2, 5], [0, 5]]

Output: [1, -1, -3]

Subtract the prefix before each range from the prefix through its end.

Constraints

  • 1–64 integers; at most 32 queries.
  • Every query satisfies 0 ≤ left ≤ right < nums.length.
  • Negative values are allowed.

Use the simulator

Change the input, then choose Visualize input. Use Next and Previous to inspect each decision, or Play to advance automatically. Compare approaches and their complexity. Choose Try yourself to write JavaScript, select My code and Visualize code to inspect its execution, or Run Tests to check results.

Execution happens in your browser. Drafts are saved locally; avoid entering secrets or sensitive information.

Related concepts and complexity