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
INPUT ARRAYBLOCK STRUCTUREQUERY RESULT1234501234Query Range: [1, 3]Need sum of indices 1,2,3Block 0Block 1[1,2] Sum=3[3,4] Sum=7Block 2[5] Sum=51Scan partial: 22Use Block 1: 73Total: 2 + 7 = 9RESULT: 9Sum of range [1,3]Complexity Analysis:Time: O(√n)Space: O(√n)Scanned: 1 partial element+ 1 complete blockKey Insight:Square root decomposition achieves O(√n) complexity by processingcomplete blocks in O(1) time and scanning at most 2√n edge elements.TutorialsPoint - Square Root Decomposition | Advanced Data Structure
Asked in
Google 12 Microsoft 8 Amazon 6 Facebook 4
12.4K Views
Medium Frequency
~35 min Avg. Time
185 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen