ADVANCED DATA STRUCTURES PROGRAM • LEVEL 21 — PLACEMENT-ORIENTED STRUCTURES

Apply Range Updates with Lazy Propagation

Learn how to apply range updates with lazy propagation using a clear C program.

AdvancedInterview patternRange and stream queries

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Point 2 = 7 Point 4 = 2

COMPLETE C PROGRAM

Complete C implementation

ads-lazy-segment-tree-range-update.c
Open in compiler
#include <stdio.h>

void push(int tree[],int lazy[],int node,int left,int right){if(lazy[node]){tree[node]+=(right-left+1)*lazy[node];if(left!=right){lazy[node*2]+=lazy[node];lazy[node*2+1]+=lazy[node];}lazy[node]=0;}}void update(int tree[],int lazy[],int node,int left,int right,int ql,int qr,int value){push(tree,lazy,node,left,right);if(qr<left||right<ql)return;if(ql<=left&&right<=qr){lazy[node]+=value;push(tree,lazy,node,left,right);return;}int middle=(left+right)/2;update(tree,lazy,node*2,left,middle,ql,qr,value);update(tree,lazy,node*2+1,middle+1,right,ql,qr,value);tree[node]=tree[node*2]+tree[node*2+1];}int query(int tree[],int lazy[],int node,int left,int right,int index){push(tree,lazy,node,left,right);if(left==right)return tree[node];int middle=(left+right)/2;return index<=middle?query(tree,lazy,node*2,left,middle,index):query(tree,lazy,node*2+1,middle+1,right,index);}

int main(void)
{
    int tree[40]={0},lazy[40]={0};update(tree,lazy,1,0,4,1,3,5);update(tree,lazy,1,0,4,2,4,2);printf("Point 2 = %d Point 4 = %d\n",query(tree,lazy,1,0,4,2),query(tree,lazy,1,0,4,4));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

Point 2 = 7 Point 4 = 2
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Delay a fully covered range update at its node and push it only when descendants are needed.
  3. Display the computed result.

Delay a fully covered range update at its node and push it only when descendants are needed.

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.