Skip to content

Concept of prefix

Course: Intro Class 2- DSA - chapter 2

A prefix is a letter or group of letters, for example ‘un-’ or ‘multi-’, which is added to the beginning of a word in order to form a different word.

Example, unmanageable, unhappy

Any continuous segment of array starting from index 0 is a prefix

Example:

Array = [1, 2, 3, 4, 5]

Prefixes:

[1]

[1, 2]

[1, 2, 3]

[1, 2, 3, 4]

[1, 2, 3, 4, 5]

It is a sum array that we create from main array, where prefix_sum[i] = sum of all the elements of the array from 0 to i

How do we calculate prefix sum?

Brute force

Steps:

  1. Loop from 0 to n. Let’s say looping variable is i
  2. For each i, to get the prefix sum at i, we need to sum all elements from 0 to i. Run another loop from 0 to i and add all elements
  3. Store the sum in prefix_sum[i]
int prefix_sum[n] = {0}
for(int i=0; i<n; i++) {
sum = 0;
for(int j=0; j<=i; j++) {
sum += arr[j];
}
prefix_sum[i] = sum;
}
Optimal

Let’s think it a bit mathematically. What is prefix_sum[i] and prefix_sum[i-1]?

prefix_sum[i] = arr[0] + arr[1] + arr[2] + … + arr[i-1] + arr[i]

prefix_sum[i-1] = arr[0] + arr[1] + arr[2] + … + arr[i-1]

We can see the common parts, arr[0] + arr[1] + … + arr[i-1]

So, prefix_sum[i] = prefix_sum[i-1] + arr[i].

🚧 Use the above for i = 1 to n-1 but not 0. As prefix_sum[i-1] is not valid. Populate prefix_sum[0] = arr[0] separately.

int prefix_sum[n] = {0};
prefix_sum[0] = arr[0];
for(int i=0; i<n; i++) {
prefix_sum[i] = prefix_sum[i-1] + arr[i]
}