Skip to main content
LeetCode 327, Hard. Topics: Array, Binary Search, Divide and Conquer, Binary Indexed Tree, Segment Tree, Merge Sort, Ordered Set. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 23 parametrized pytest cases, and a playground notebook:

Problem

<p>Given an integer array <code>nums</code> and two integers <code>lower</code> and <code>upper</code>, return <em>the number of range sums that lie in</em> <code>[lower, upper]</code> <em>inclusive</em>.</p> <p>Range sum <code>S(i, j)</code> is defined as the sum of the elements in <code>nums</code> between indices <code>i</code> and <code>j</code> inclusive, where <code>i <= j</code>.</p>

Examples

Constraints

<ul> <li><code>1 <= nums.length <= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li> <li><code>-10<sup>5</sup> <= lower <= upper <= 10<sup>5</sup></code></li> <li>The answer is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li> </ul>

Solution

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

Complexity

Tags

Last modified on September 7, 2026