Skip to content

Latest commit

 

History

History
33 lines (17 loc) · 1.41 KB

File metadata and controls

33 lines (17 loc) · 1.41 KB

What is a prefix sum algorithm and why you need it ?

By Defination:

It is a simple yet powerful technique that allows to perform fast calculation on the sum of elements in a given range (called contiguos segment of an array).

Example:

image

image

👉 Here A[i] = sum of all elements from 0 to i.

image

As mentioned above 👆 sum between range 0 to 4 : would be A[4] , which implies all elements between 0 to 4.

image

Why it is done in this way:

From the prefix sum array we only have following data:

prefix_sum[i] = Sum of all elements between 0 to i.

So we only have prefix sum data for a range where start range is always 0 and the end range can be any value < len(input array). So when we are given a range where start element is a non zero value , we should break the given range to a equation which can be represented with a range where start element can be 0.

Example :

range-sum-query-immutable