Solved Problem - Subarray Sum

In this lesson, we'll see an effective way to compute sum of an subarray.

Problem statement

Given an array, AA, of NN integers, answer QQ queries of the type (l,r)(l, r) - sum of the elements in the subarray A[l...r]A[l...r]. Print the sum for each query.

Input format

The first line contains two space-separated integers NN and QQ (1N,Q106)(1 \leq N,Q \leq 10^6).

The second line contains NN integers representing the array A[]A[] (1A[i]106)(1 \leq A[i] \leq 10^6).

The next QQ lines each contain a pair of integers ll and rr.

Output format

Print QQ integers and answer to the queries.


Sample

Input

5 3
1 2 4 8 16
1 5
2 3
3 5

Output

31 6 28

Brute force

The brute force method would be to loop over the subarray in the query and sum all the elements.

I am skipping the code for this solution because it is trivial.

The time for each query would be O(N)O(N), the total complexity of the solution would be O(QN)O(Q*N). This means it is not good enough for the given constraints.

Optimization

First, let’s discuss what the prefix sum array is.

The prefix sum array sum[]sum[] of an array A[]A[] is defined as

sum[i]=k=1iA[k]sum[i] = \sum_{k=1}^{i} A[k]

or, iith element of sum[]sum[] is sum of first ii elements of A[]A[]

We can use the prefix sum array to find the sum of a subarray in O(1)O(1) time.

sum[i...j]=A[i]+A[i+1]+...+A[j]sum[i...j] = A[i] + A[i+1] + ... + A[j]

== (A[1]+A[2]+...+A[j])(A[1]+A[2]+...+A[i1])(A[1] + A[2] + ... +A[j]) - (A[1] + A[2] + ... +A[i-1])

== sum[j]sum[i1]sum[j] - sum[i-1]

From preprocessing to computing the sum[]sum[] array takes O(N)O(N) time. Each query is just O(1)O(1).

So the total time complexity is O(N+Q)O(N + Q).

See the below illustration for a better understanding.

Get hands-on with 1400+ tech skills courses.