DSA
    advanced

    Fenwick Tree (Binary Indexed Tree)

    Fenwick Tree (Binary Indexed Tree)

    A simpler, more space-efficient alternative to Segment Tree for prefix sums and point updates. Uses bit manipulation for elegant O(log n) operations.

    ⏱ O(log n)
    💾 O(n)
    Ready
    Phase: Building BIT
    Original Array (0-indexed)
    0
    3
    1
    2
    2
    -1
    3
    6
    4
    5
    5
    4
    6
    -3
    7
    3
    Fenwick Tree Array (1-indexed) — BIT[i] stores sum of {i - (i & -i) + 1 .. i}
    1
    0
    r=1
    2
    0
    r=2
    3
    0
    r=1
    4
    0
    r=4
    5
    0
    r=1
    6
    0
    r=2
    7
    0
    r=1
    8
    0
    r=8
    r = i & (-i) = responsibility (how many elements this index covers)

    Input: [3, 2, -1, 6, 5, 4, -3, 3]. BIT uses bit manipulation to store partial sums. Each index i stores sum of i & (-i) elements ending at i.

    50%
    Live Variables
    n8

    Prefix sum query

    Sequence

    Order the steps of query(i) on a Fenwick tree.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    What does i & (-i) compute?

    The short version

    Like a skip list for sums. Instead of storing every prefix sum, you store clever partial sums at specific positions. Using binary representation, you can 'hop' through just log(n) positions to get any prefix sum.

    In more depth

    Elegant Bit Manipulation

    Fenwick Tree (BIT) achieves the same query/update complexity as Segment Tree with simpler code and less space.

    Core Operations:

    Update(i, delta):
      while i <= n:
        tree[i] += delta
        i += i & (-i)  // Move to parent
    
    Query(i):  // Sum from 1 to i
      sum = 0
      while i > 0:
        sum += tree[i]
        i -= i & (-i)  // Move to predecessor

    Range Query: sum(l, r) = Query(r) - Query(l-1)

    Key Gotchas:

    Uses 1-based indexing (add 1 to all indices)
    i & (-i) gives lowest set bit
    Cannot do range min/max (Segment Tree needed)

    When to reach for this

    • Prefix sum queries + point updates
    • Counting inversions
    • Dynamic rank queries
    • Simpler than Segment Tree when range updates not needed

    Interview Questions

    Google
    Google
    Amazon
    Google
    Amazon
    Google
    Amazon
    Microsoft
    Bloomberg

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required