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.

AdvancedInterview patternRange and stream queries

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Sum[1,3] = 15

COMPLETE C PROGRAM

Complete C implementation

ads-segment-tree-range-sum.c
Open in compiler
#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;
}

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

Sum[1,3] = 15
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Decompose a query interval into fully covered segment-tree nodes.
  3. 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.