Skip to main content

Prefix Sums for Range Sum Queries in Java and Python

Build a prefix sum array in O(n) time, then answer each half-open range sum query in O(1) time in Java and Python.

Problem and input contract

Build a prefix array for a fixed sequence of n signed 32-bit integers. Each query uses zero-based bounds 0 ≤ left ≤ right ≤ n and returns the sum of elements from left up to right exclusive.

For [3, −2, 5, 1], [1, 3) returns 3 and [0, 4) returns 7. The empty array supports [0, 0), which returns 0. Two maximum Java int values sum to 4294967294.

Worked example

For [3, −2, 5, 1], the sum over [1, 3) is 3.

Start with 0, then append 3, 1, 6, and 7. For [1, 3), subtract prefix[1] = 3 from prefix[3] = 6. The result is 3, the sum of −2 and 5.

How the solution works

Each prefix stores the sum before its index. Subtract the prefix ending before left from the prefix ending before right.

Keep the initial zero so a range starting at index 0 uses the same subtraction. Require 0 ≤ left ≤ right ≤ n. Java uses long because sums can exceed int even when every input fits.

Python solution

def prefix_sums(nums):
    prefix = [0]
    for value in nums:
        prefix.append(prefix[-1] + value)
    return prefix

def range_sum(prefix, left, right):
    return prefix[right] - prefix[left]

Java solution

class Solution {
    static long[] prefixSums(int[] nums) {
        long[] prefix = new long[nums.length + 1];
        for (int i = 0; i < nums.length; i++) {
            prefix[i + 1] = prefix[i] + nums[i];
        }
        return prefix;
    }
    static long rangeSum(long[] prefix, int left, int right) {
        return prefix[right] - prefix[left];
    }
}

Approaches and complexity

Scanning each range costs O(right − left) and uses O(1) auxiliary space. Building the prefix array takes O(n) time and O(n) storage, then each query needs two reads and one subtraction. The preprocessing pays off when queries repeatedly cover long ranges.

Approach comparison
ApproachTimeAuxiliary spaceAdvantageLimitationUse case
Range scanO(k) per queryO(1)No preprocessingRepeats workFew short queries
Prefix sumsO(n) build, O(1) queryO(n)Two reads per queryRebuild after updatesRepeated queries on fixed data

Common mistakes and interview follow-up

Build n + 1 entries so prefix[0] is zero. Convert inclusive ranges to half-open ranges by increasing the right endpoint by one. For frequent updates, consider a Fenwick tree.

Related practice: Find the First Occurrence with Binary Search.

Comments

Popular posts from this blog

Minimum Window Substring: Efficient Algorithm for Finding the Shortest Substring

The Minimum Window Substring problem is a classic string manipulation challenge that tests our algorithmic skills. In this blog, we will explore an efficient solution to find the minimum window substring in a given string. We will provide implementation examples in both Java and Python, enabling you to grasp the concepts and apply them to your own coding projects.   Understanding the Problem: Given a string and a target pattern, our objective is to find the minimum window substring in the given string that contains all the characters of the target pattern. The minimum window substring refers to the shortest possible substring that satisfies this condition.   Approach: To solve the Minimum Window Substring problem, we can use the sliding window technique. This approach involves maintaining a window of characters in the string and adjusting its size based on certain conditions. The key steps of the algorithm are as follows: Create two pointers, left and right, to define the windo...

Longest Palindromic Substring: Explained with Java and Python Code

The Longest Palindromic Substring problem is a classic challenge in the realm of string manipulation. In this blog, we will delve into the intricacies of finding the longest palindromic substring in a given string. Through a step-by-step approach and illustrative examples, you will gain a comprehensive understanding of the problem and learn how to solve it efficiently.   Understanding the Problem: A palindrome is a string that reads the same forward and backward. The Longest Palindromic Substring problem requires finding the longest substring within a given string that is also a palindrome. Our goal is to determine the length of this substring and return the substring itself.   Approach: To solve the Longest Palindromic Substring problem, we can employ a dynamic programming approach or use the expanding around center technique. Here, we will explore the dynamic programming approach. Create a boolean table, dp, of size [n][n] (where n is the length of the input string) to store ...