VOOZH about

URL: https://www.geeksforgeeks.org/dsa/segment-tree-for-range-assignment-and-range-sum-queries/

⇱ Segment Tree for Range Assignment and Range Sum Queries - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Segment Tree for Range Assignment and Range Sum Queries

Last Updated : 2 Jan, 2026

Given an array of size filled with all 0s, the task is to answer queries, where the queries can be one of the two types:

  • Type 1 (1, L, R, X): Assign value X to all elements on the segment from L to R, and
  • Type 2 (2, L, R): Find the sum on the segment from L to R.

Examples:

Input: N = 5, Q = 3, queries[][] = [[1, 0, 2, 5], [2, 1, 3], [1, 2, 3, 10]]
Output: 10
Explanation:
Initially, the array is {0, 0, 0, 0, 0}
The first query assigns value 5 to indices 0 through 2, so the array becomes {5, 5, 5, 0, 0}
The second query asks for the sum from indices 1 through 3, which is 5 + 5 + 0 = 10
The third query assigns value 10 to indices 2 through 3, so the array becomes {5, 5, 10, 10, 0}

Input: N = 10, Q = 4, queries[q][4] = [[1, 0, 4, 3], [2, 2, 6], [1, 4, 8, 2], [2, 0, 8]]
Output: [9, 22]
Explanation:
Initially, the array is {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
After assigning value 3 to indices 0 through 4, the array becomes {3, 3, 3, 3, 3, 0, 0, 0, 0, 0}
The second query computes the sum from indices 2 through 6, which is 3 + 3 + 3 + 0 + 0 = 9
Next, assigning value 2 to indices 4 through 8, the array becomes {3, 3, 3, 3, 2, 2, 2, 2, 2, 0}
The final query asks for the sum from indices 0 through 8, which is 3 + 3 + 3 + 3 + 2 + 2 + 2 + 2 + 2 = 22

[Approach] Using Segment Tree with Lazy Propagation - O(Q log(N)) Time and O(N) Space

We use a segment tree with lazy propagation. The segment tree stores the sum of segments of the array, allowing range sum queries to be answered in O(log N) time. Each node of the tree represents a segment, and its value is the sum of all elements in that segment.

Lazy propagation is used to efficiently support range assignment updates. When an update completely covers a segment, instead of immediately updating all its children, we store the assignment in a lazy array. This deferred update is applied only when that segment is accessed again, either during another update or a query. This avoids unnecessary work and keeps the operations efficient.

During a range update, if the current segment lies entirely within the update range, we directly update the node and mark its children as lazy. If the segment partially overlaps, we push any pending updates and recursively update both children, then recompute the current node’s sum.

For range sum queries, any pending lazy updates are applied before accessing the node. If the segment is fully inside the query range, its stored sum is returned. Otherwise, the query is propagated to the left and right children, and their results are added


Output
3 8 


Comment