Solved Problem - Subarray Sum
In this lesson, we'll see an effective way to compute sum of an subarray.
We'll cover the following
Problem statement
Given an array, , of integers, answer queries of the type - sum of the elements in the subarray . Print the sum for each query.
Input format
The first line contains two space-separated integers and .
The second line contains integers representing the array .
The next lines each contain a pair of integers and .
Output format
Print 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 , the total complexity of the solution would be . 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 of an array is defined as
or, th element of is sum of first elements of
We can use the prefix sum array to find the sum of a subarray in time.
From preprocessing to computing the array takes time. Each query is just .
So the total time complexity is .
See the below illustration for a better understanding.
Get hands-on with 1400+ tech skills courses.