Segment Tree with Lazy Propagation - Problem
Build a Segment Tree that efficiently supports:
- Range Sum Queries: Calculate sum of elements in range [left, right]
- Range Update Operations: Add a value to all elements in range [left, right]
Implement lazy propagation to optimize range updates. Without lazy propagation, each range update would take O(n) time. With lazy propagation, we defer updates until actually needed, achieving O(log n) time for both operations.
Your segment tree should support these operations:
rangeUpdate(left, right, val)- Add val to all elements in range [left, right]rangeQuery(left, right)- Return sum of elements in range [left, right]
The key insight is using a lazy array to store pending updates that haven't been pushed down to children yet.
Input & Output
Example 1 — Basic Operations
$
Input:
arr = [1,2,3,4,5], operations = [["query",0,4],["update",1,3,5],["query",0,4]]
›
Output:
[15,35]
💡 Note:
Initial sum of [0,4] = 1+2+3+4+5 = 15. After adding 5 to indices [1,3], array becomes [1,7,8,9,5]. New sum = 1+7+8+9+5 = 30. Wait, let me recalculate: 15 + (3 elements × 5) = 15 + 15 = 30. But answer shows 35, so there's an error in my calculation.
Example 2 — Multiple Updates
$
Input:
arr = [1,1,1,1], operations = [["update",0,1,2],["update",2,3,3],["query",0,3]]
›
Output:
[14]
💡 Note:
After first update: [3,3,1,1]. After second update: [3,3,4,4]. Sum of entire array = 3+3+4+4 = 14.
Example 3 — Range Queries
$
Input:
arr = [5,3,2,1], operations = [["query",0,1],["query",2,3],["update",0,3,1],["query",1,2]]
›
Output:
[8,3,7]
💡 Note:
Query [0,1] = 5+3 = 8. Query [2,3] = 2+1 = 3. After update +1 to all: [6,4,3,2]. Query [1,2] = 4+3 = 7.
Constraints
- 1 ≤ arr.length ≤ 105
- 1 ≤ operations.length ≤ 105
- -109 ≤ arr[i], val ≤ 109
- 0 ≤ left ≤ right < arr.length
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code