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
INPUTFENWICK TREERESULTSArray: [1,3,5,2,4]13524Operations:1. query(2) → sum[0..2]2. update(1, 2) → add 2 to arr[1]3. query(2) → sum[0..2] again1Tree Structure (1-indexed)2345T[1]=1T[2]=4T[3]=5T[4]=11T[5]=4Query(2): traverse T[3]+T[2]= 5 + 4 = 9Update(1,2): modify T[2], T[4]T[2]+=2, T[4]+=2Query(2): traverse T[3]+T[2]= 5 + 6 = 11Query Results[9, 11]First query: 1+3+5 = 9After update(1,2):arr becomes [1,5,5,2,4]Second query: 1+5+5 = 11Time ComplexityO(log n) per operationvs O(n) brute forceKey Insight:Binary indexed tree uses bit manipulation (idx & -idx) to access parent/child nodes,enabling logarithmic time complexity for both range queries and point updates.TutorialsPoint - Fenwick Tree (Binary Indexed Tree) | Optimized Approach
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
25.8K Views
Medium Frequency
~35 min Avg. Time
890 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