DATA STRUCTURES PROGRAM • ARRAY TECHNIQUES

Answer Range-Sum Queries with Prefix Sums

Learn how to answer range-sum queries with prefix sums using a clear C program.

BeginnerPrefix sumRange queryPreprocessing

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Range sum [1,4] = 11

COMPLETE C PROGRAM

Complete C implementation

dsa-prefix-sum-range-query.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int values[] = {3, 1, 4, 1, 5, 9};
    int prefix[7] = {0};
    for (int index = 0; index < 6; index++) prefix[index + 1] = prefix[index] + values[index];
    int left = 1, right = 4;
    printf("Range sum [%d,%d] = %d\n", left, right, prefix[right + 1] - prefix[left]);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Range sum [1,4] = 11
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Store cumulative sums so a range is the difference between two prefix positions.
  3. Display the computed result.

Store cumulative sums so a range is the difference between two prefix positions.

EFFICIENCY

Time and space complexity

Time complexity

O(n) preprocessing, O(1) query

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.