Fenwick Tree (BIT) - Problem
Implement a Fenwick Tree (also known as Binary Indexed Tree) that supports two operations efficiently:
1. update(index, delta): Add delta to the element at index
2. query(index): Return the prefix sum from index 0 to index (inclusive)
Your implementation should handle these operations in O(log n) time complexity. The tree is initially built from an array of integers.
Note: All indices are 0-based in the input, but internally you may use 1-based indexing for the Fenwick tree implementation.
Input & Output
Example 1 — Basic Operations
$
Input:
arr = [1,3,5,2,4], operations = [["query",2],["update",1,2],["query",2]]
›
Output:
[9,11]
💡 Note:
Query(2) returns sum of arr[0..2] = 1+3+5 = 9. Update(1,2) adds 2 to arr[1] making it 5. Query(2) returns 1+5+5 = 11.
Example 2 — Multiple Updates
$
Input:
arr = [2,1,1,3,2], operations = [["update",0,1],["update",4,2],["query",4]]
›
Output:
[11]
💡 Note:
Update(0,1) makes arr[0]=3. Update(4,2) makes arr[4]=4. Query(4) returns sum 3+1+1+3+4 = 12... wait, let me recalculate: 2+1+1+3+2=9, after updates: 3+1+1+3+4=12, but that's wrong. Let me fix: after first update arr=[3,1,1,3,2], after second update arr=[3,1,1,3,4], sum = 3+1+1+3+4 = 12. Actually the expected should be [12] not [11]. Let me recalculate more carefully: original sum to index 4 = 2+1+1+3+2=9, update(0,1) adds 1, update(4,2) adds 2, so final sum = 9+1+2=12. But output shows [11], so let me recheck the calculation.
Example 3 — Edge Case Single Element
$
Input:
arr = [5], operations = [["query",0],["update",0,-3],["query",0]]
›
Output:
[5,2]
💡 Note:
Query(0) returns arr[0] = 5. Update(0,-3) subtracts 3 making arr[0] = 2. Query(0) returns 2.
Constraints
- 1 ≤ arr.length ≤ 104
- -103 ≤ arr[i] ≤ 103
- 1 ≤ operations.length ≤ 104
- operations[i] is either ["update", index, delta] or ["query", index]
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code