ADVANCED DATA STRUCTURES PROGRAM • LEVEL 21 — PLACEMENT-ORIENTED STRUCTURES
Answer Range Sums with a Segment Tree
Learn how to answer range sums with a segment tree using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Sum[1,3] = 15
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
void build(const int a[],int t[],int node,int left,int right){if(left==right){t[node]=a[left];return;}int middle=(left+right)/2;build(a,t,node*2,left,middle);build(a,t,node*2+1,middle+1,right);t[node]=t[node*2]+t[node*2+1];}int query(const int t[],int node,int left,int right,int ql,int qr){if(qr<left||right<ql)return 0;if(ql<=left&&right<=qr)return t[node];int middle=(left+right)/2;return query(t,node*2,left,middle,ql,qr)+query(t,node*2+1,middle+1,right,ql,qr);}
int main(void)
{
int values[]={1,3,5,7,9,11},tree[24]={0};build(values,tree,1,0,5);printf("Sum[1,3] = %d\n",query(tree,1,0,5,1,3));return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Sum[1,3] = 15
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Decompose a query interval into fully covered segment-tree nodes.
- Display the computed result.
Decompose a query interval into fully covered segment-tree nodes.
EFFICIENCY
Time and space complexity
Time complexity
O(log n) 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.
