Square Root Decomposition - Problem
Implement square root decomposition for efficient range sum queries and point updates on an array.
You are given an array of integers and need to support two operations:
query(left, right): Return the sum of elements from index left to right (inclusive)update(index, value): Update the element at index to value
The goal is to achieve O(√n) time complexity for both operations by dividing the array into blocks of size √n.
Return an array containing the results of all query operations in order.
Input & Output
Example 1 — Basic Range Query and Update
$
Input:
arr = [1,2,3,4,5], operations = [["query",1,3],["update",2,10],["query",1,3]]
›
Output:
[9,16]
💡 Note:
First query [1,3]: 2+3+4=9. Update index 2 to 10. Second query [1,3]: 2+10+4=16.
Example 2 — Full Range Query
$
Input:
arr = [1,2,3,4], operations = [["query",0,3]]
›
Output:
[10]
💡 Note:
Query entire array [0,3]: 1+2+3+4=10.
Example 3 — Single Element Operations
$
Input:
arr = [5], operations = [["query",0,0],["update",0,7],["query",0,0]]
›
Output:
[5,7]
💡 Note:
Query single element: 5. Update to 7. Query again: 7.
Constraints
- 1 ≤ arr.length ≤ 104
- -109 ≤ arr[i] ≤ 109
- 1 ≤ operations.length ≤ 104
- operations[i] is either ["query", left, right] or ["update", index, value]
- 0 ≤ left ≤ right < arr.length
- 0 ≤ index < arr.length
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code