Bird
0
0
DSA Cprogramming

Prefix Sum Array in DSA C

Choose your learning style9 modes available
Mental Model
A prefix sum array stores sums of elements from the start up to each position, so you can quickly find the sum of any part of the original array.
Analogy: Imagine a row of buckets where each bucket holds the total amount of water collected from the first bucket up to that bucket. To find how much water is between two buckets, you just subtract the amounts in these buckets.
Original array:  [2] -> [4] -> [6] -> [8] -> [10]
Prefix sums:     [2] -> [6] -> [12] -> [20] -> [30]
Dry Run Walkthrough
Input: array: [2, 4, 6, 8, 10]
Goal: Build a prefix sum array where each element is the sum of all elements before it including itself
Step 1: Start with prefix[0] = array[0]
Prefix sums: [2] -> null
Why: The first prefix sum is just the first element itself
Step 2: Calculate prefix[1] = prefix[0] + array[1] = 2 + 4
Prefix sums: [2] -> [6] -> null
Why: Add current element to sum of all previous elements
Step 3: Calculate prefix[2] = prefix[1] + array[2] = 6 + 6
Prefix sums: [2] -> [6] -> [12] -> null
Why: Keep adding current element to running total
Step 4: Calculate prefix[3] = prefix[2] + array[3] = 12 + 8
Prefix sums: [2] -> [6] -> [12] -> [20] -> null
Why: Continue accumulating sums
Step 5: Calculate prefix[4] = prefix[3] + array[4] = 20 + 10
Prefix sums: [2] -> [6] -> [12] -> [20] -> [30] -> null
Why: Final prefix sum includes all elements
Result:
Prefix sums: [2] -> [6] -> [12] -> [20] -> [30] -> null
Annotated Code
DSA C
#include <stdio.h>
#include <stdlib.h>

void buildPrefixSum(int* arr, int n, int* prefix) {
    if (n == 0) return; // handle empty array gracefully
    prefix[0] = arr[0]; // start with first element
    for (int i = 1; i < n; i++) {
        prefix[i] = prefix[i - 1] + arr[i]; // add current element to previous sum
    }
}

void printArray(int* arr, int n) {
    for (int i = 0; i < n; i++) {
        printf("%d", arr[i]);
        if (i != n - 1) printf(" -> ");
    }
    printf(" -> null\n");
}

int main() {
    int arr[] = {2, 4, 6, 8, 10};
    int n = sizeof(arr) / sizeof(arr[0]);
    int* prefix = (int*)malloc(n * sizeof(int));

    buildPrefixSum(arr, n, prefix);

    printf("Original array: ");
    printArray(arr, n);

    printf("Prefix sums:    ");
    printArray(prefix, n);

    free(prefix);
    return 0;
}
prefix[0] = arr[0]; // start with first element
initialize prefix sum with first element of array
for (int i = 1; i < n; i++) { prefix[i] = prefix[i - 1] + arr[i]; // add current element to previous sum }
accumulate sums by adding current element to previous prefix sum
OutputSuccess
Original array: 2 -> 4 -> 6 -> 8 -> 10 -> null Prefix sums: 2 -> 6 -> 12 -> 20 -> 30 -> null
Complexity Analysis
Time: O(n) because we visit each element once to build the prefix sums
Space: O(n) because we create a new array to store prefix sums of the same size as input
vs Alternative: Without prefix sums, summing any subarray takes O(k) time; prefix sums reduce this to O(1) after O(n) preprocessing
Edge Cases
empty array
no prefix sums are created; code should handle gracefully
DSA C
for (int i = 1; i < n; i++) { ... } handles zero iterations if n=0
single element array
prefix sum array equals the original single element
DSA C
prefix[0] = arr[0]; handles single element initialization
When to Use This Pattern
When you need to quickly find sums of parts of an array multiple times, use prefix sums to speed up repeated sum queries.
Common Mistakes
Mistake: Starting prefix sum from index 1 without initializing prefix[0]
Fix: Always set prefix[0] = arr[0] before the loop to avoid incorrect sums
Mistake: Adding arr[i] to arr[i-1] instead of prefix[i-1]
Fix: Add current element to prefix[i-1], not arr[i-1], to accumulate sums correctly
Summary
It builds an array where each position holds the sum of all elements up to that position.
Use it when you want to find sums of any subarray quickly after one-time setup.
The key is to keep adding the current element to the sum of all previous elements.