We have an array arr[0 . . . n-1]. We should be able to Find the sum of elements from index l to r where 0 <= l <= r <= n-1.
A simple solution is to run a loop from l to r and calculate sum of elements in given range. The operation takes O(n) time .
Another solution is to create another array and store sum from start to i at the ith index in this array. Sum of a given range can now be calculated in O(1) time.
In the first example the complexity is O(n) understood because it is traversing each element of the array. But in second solution how the complexity is O(1).
Please help me to understand this.
O(n)time on precalculating cumulative sums, so thatsum[i]is the sum of all elements from0toi. To find the sum of elements between indicesiandj, you only need to fetchsum[i]andsum[j], and subtract them. Accessing array items isO(1), since it involves only a single read from a known location, and2 * O(1)is stillO(1), as @Henk wrote above. - Groo