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.

AdvancedInterview patternRange and stream queries

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Sum[1,4] = 14

COMPLETE C PROGRAM

Complete C implementation

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

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,4] = 14
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Store partial sums indexed by the least significant set bit and subtract two prefixes.
  3. 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.