Skip to main content
LeetCode 303, Easy. Topics: Array, Design, Prefix Sum. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 12 parametrized pytest cases, and a playground notebook:

Problem

Given an integer array nums, handle multiple queries of the following type:
  1. Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.
Implement the NumArray class:
  • NumArray(int[] nums) Initializes the object with the integer array nums.
  • int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).

Examples

Constraints

  • 1 <= nums.length <= 10<sup>4</sup>
  • -10<sup>5</sup> <= nums[i] <= 10<sup>5</sup>
  • 0 <= left <= right < nums.length
  • At most 10<sup>4</sup> calls will be made to sumRange.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026