Interval Sum

Question (LC.206)

Given an array of integers and a list of intervals, return a list of interval sums.

Example

I: [1,2,7,8,5]
Q1: (0, 4) => 1+2+7+8+5
Q2: (1, 2) => 2+7
Q3: (2, 4) => 7+8+5

Approach

  1. Build a prefix sum array

  2. Write a query interval helper function

Code

public ArrayList<Long> intervalSum(int[] A, ArrayList<Interval> queries) {
    ArrayList<Long> results = new ArrayList<>();
    if (A == null || A.length == 0) {
        return results;
    }
    long[] preSum = prefixSum(A);
    for (Interval query : queries) {
        results.add(getIntvSum(preSum, query));
    }
    return results;
}

// [0, 1, 3, 10, 18, 23]
private long[] prefixSum(int[] nums) {
    long[] preSum = new long[nums.length + 1];
    preSum[0] = 0;
    long curSum = 0;
    for (int i = 0; i < nums.length; i++) {
        curSum += nums[i];
        preSum[i + 1] = curSum;
    }
    return preSum;
}

private long getIntvSum(long[] preSum, Interval query) {
    return preSum[query.end + 1] - preSum[query.start];
}

Time & Space Complexity

The running sum takes O(n) extra space. But the range query only takes O(1) time to process.

Follow Up (LC.207)

Add another function modify that can update the value of A at a given index.

Example

Analysis

The prefix sum approach is not so good of an idea now since updating one value will result in updating all the prefix sum after that index. We want a structure that's easy to make updates.

Behold, Segment Tree

The data variable in the segment tree will hold the sum value. Then, we need build the segment tree off the given array. Query and modify should be easy to implement after constructing the tree.

Segment Tree Code

Definition

Build

Range Query

Update Query

Time & Space Complexity

The segment tree will still take O(n) extra space. But the range queries and update queries only take O(logn) time.

Last updated