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.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Range sum [1,4] = 11
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Range sum [1,4] = 11
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Store cumulative sums so a range is the difference between two prefix positions.
- 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.
