codeintuition-logo

Understanding the prefix sum pattern


Some problems involving sequential data structures (like arrays) require us to know the aggregated value of some function f over all subarrays. For some functions f like the sum function, these values can be easily derived from a corresponding prefix sum data structure. A prefix sum data structure stores the aggregated value of f for all prefixes for the given sequence. 

Consider we have an array arr and a function f where agg[i] is the aggregated value of f over arr[0] .. arr[i]. A prefix sum data structure is one where we map the index i to agg[i]. In most cases, we can use an array as a prefix sum data structure by storing agg[i] at the index i as we can easily access aggregated values of prefixes using indices.

Loading Image

Use array as prefix sum data structure

Liking the course? Check our discounted plans to continue learning.