Math Fundamentals18 sections · 814 units
Open in Course

Range Sum - Implementation

In pseudocode

Here's the solution:


class NumArray
    prefix := array

    function constructor(nums)
        n := length of nums
        prefix := array of size n
        prefix[0] := nums[0]
        for i from 1 to n - 1
            prefix[i] := prefix[i - 1] + nums[i]

    function sumRange(i, j)
        if i = 0 then
            return prefix[j]
        else
            return prefix[j] - prefix[i - 1]

The constructor takes O(n)O(n) time to build the prefix array. Each query takes O(1)O(1) time. This trades space for speed.