ADVANCED DATA STRUCTURES PROGRAM • LEVEL 21 — PLACEMENT-ORIENTED STRUCTURES
Answer Range Sums with a Fenwick Tree
Learn how to answer range sums with a fenwick tree using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Sum[1,4] = 14
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
void update(int tree[],int count,int index,int delta){for(;index<=count;index+=index&-index)tree[index]+=delta;}int query(const int tree[],int index){int sum=0;for(;index>0;index-=index&-index)sum+=tree[index];return sum;}
int main(void)
{
int values[]={1,2,3,4,5,6},tree[7]={0};for(int i=0;i<6;i++)update(tree,6,i+1,values[i]);printf("Sum[1,4] = %d\n",query(tree,5)-query(tree,1));return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Sum[1,4] = 14
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Store partial sums indexed by the least significant set bit and subtract two prefixes.
- Display the computed result.
Store partial sums indexed by the least significant set bit and subtract two prefixes.
EFFICIENCY
Time and space complexity
Time complexity
O(log n) update/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.
