DSA Explorer
QuicksortMerge SortBubble SortInsertion SortSelection SortHeap SortCounting SortRadix SortBucket SortShell SortTim SortCocktail Shaker SortComb SortGnome SortPancake SortPatience SortCycle SortStrand SortWiggle Sort (Wave Sort)Bead Sort (Gravity Sort)Binary Insertion SortBitonic SortBogo Sort (Stupid Sort)Stooge SortOdd-Even Sort (Brick Sort)Pigeonhole SortIntro Sort (Introspective Sort)Tree Sort (BST Sort)Dutch National Flag (3-Way Partitioning)
Binary SearchLinear SearchJump SearchInterpolation SearchExponential SearchTernary SearchFibonacci SearchQuick Select (k-th Smallest)Median of Medians (Deterministic Select)Hill climbingSimulated AnnealingTabu SearchBinary Tree DFS SearchSentinel Linear SearchDouble Linear SearchTernary Search (Unimodal Function)Search in 2D Matrix
Binary Search Tree (BST)StackQueueHash Table (Hash Map)Heap (Priority Queue)Linked ListTrie (Prefix Tree)Binary TreeTrie (Prefix Tree)Floyd's Cycle Detection (Tortoise and Hare)Merge Two Sorted Linked ListsCheck if Linked List is PalindromeFind Middle of Linked ListBalanced Parentheses (Valid Parentheses)Next Greater ElementInfix to Postfix ConversionMin Stack (O(1) getMin)Largest Rectangle in HistogramDaily Temperatures (Monotonic Stack)Evaluate Reverse Polish NotationInfix Expression Evaluation (Two Stacks)Min Heap & Max HeapSliding Window MaximumTrapping Rain WaterRotate Matrix 90 DegreesSpiral Matrix TraversalSet Matrix ZeroesHash Table with ChainingOpen Addressing (Linear Probing)Double HashingCuckoo Hashing
Depth-First Search (DFS)Breadth-First Search (BFS)Dijkstra's AlgorithmFloyd-Warshall AlgorithmKruskal's AlgorithmPrim's AlgorithmTopological SortA* Pathfinding AlgorithmKahn's Algorithm (Topological Sort)Ford-Fulkerson Max FlowEulerian Path/CircuitBipartite Graph CheckBorůvka's Algorithm (MST)Bidirectional DijkstraPageRank AlgorithmBellman-Ford AlgorithmTarjan's Strongly Connected ComponentsArticulation Points (Cut Vertices)Find Bridges (Cut Edges)Articulation Points (Cut Vertices)Finding Bridges (Cut Edges)
0/1 Knapsack ProblemLongest Common Subsequence (LCS)Edit Distance (Levenshtein Distance)Longest Increasing Subsequence (LIS)Coin Change ProblemFibonacci Sequence (DP)Matrix Chain MultiplicationRod Cutting ProblemPalindrome Partitioning (Min Cuts)Subset Sum ProblemWord Break ProblemLongest Palindromic SubsequenceMaximal Square in MatrixInterleaving StringEgg Drop ProblemUnique Paths in GridCoin Change II (Count Ways)Decode WaysWildcard Pattern MatchingRegular Expression MatchingDistinct SubsequencesMaximum Product SubarrayHouse RobberClimbing StairsPartition Equal Subset SumKadane's Algorithm (Maximum Subarray)
A* Search AlgorithmConvex Hull (Graham Scan)Line Segment IntersectionCaesar CipherVigenère CipherRSA EncryptionHuffman CompressionRun-Length Encoding (RLE)Lempel-Ziv-Welch (LZW)Canny Edge DetectionGaussian Blur FilterSobel Edge FilterHarris Corner DetectionHistogram EqualizationMedian FilterLaplacian FilterMorphological ErosionMorphological DilationImage Thresholding (Otsu's Method)Conway's Game of LifeLangton's AntRule 30 Cellular AutomatonFast Fourier Transform (FFT)Butterworth FilterSpectrogram (STFT)
Knuth-Morris-Pratt (KMP) AlgorithmRabin-Karp AlgorithmBoyer-Moore AlgorithmAho-Corasick AlgorithmManacher's AlgorithmSuffix ArraySuffix Tree (Ukkonen's Algorithm)Trie for String MatchingEdit Distance for StringsLCS for String MatchingHamming DistanceJaro-Winkler DistanceDamerau-Levenshtein DistanceBitap Algorithm (Shift-Or, Baeza-Yates-Gonnet)Rolling Hash (Rabin-Karp Hash)Manacher's AlgorithmZ AlgorithmLevenshtein Distance

Fenwick Tree (Binary Indexed Tree - BIT)

Tree Structures
O(log n) query/update time, O(n) space
Advanced

A data structure that can efficiently update elements and calculate prefix sums in O(log n) time. Also known as Binary Indexed Tree (BIT), invented by Peter Fenwick in 1994. Fenwick trees are more space-efficient and simpler than segment trees for range sum queries, using only O(n) space compared to segment tree's O(4n).

Prerequisites:
Prefix Sums
Binary Representation
Bit Manipulation

Visualization

Interactive visualization for Fenwick Tree (Binary Indexed Tree - BIT)

Fenwick Tree (Binary Indexed Tree)

Original Array:

0
5
1
3
2
7
3
2
4
8
5
4
6
6
7
1

Fenwick Tree (1-indexed):

Update Value

Range Sum Query

• Update: O(log n) - Updates value at index and propagates changes

• Query: O(log n) - Computes prefix sum or range sum

• Space: O(n) - Efficient tree representation

Interactive visualization with step-by-step execution

Implementation

Language:
1class FenwickTree {
2  private tree: number[];
3  private n: number;
4  
5  constructor(n: number) {
6    this.n = n;
7    this.tree = new Array(n + 1).fill(0); // 1-indexed
8  }
9  
10  // Get lowest set bit
11  private LSB(x: number): number {
12    return x & (-x);
13  }
14  
15  // Add delta to index (1-indexed)
16  update(index: number, delta: number): void {
17    while (index <= this.n) {
18      this.tree[index] += delta;
19      index += this.LSB(index);
20    }
21  }
22  
23  // Get prefix sum [1, index]
24  prefixSum(index: number): number {
25    let sum = 0;
26    while (index > 0) {
27      sum += this.tree[index];
28      index -= this.LSB(index);
29    }
30    return sum;
31  }
32  
33  // Get range sum [left, right] (1-indexed)
34  rangeSum(left: number, right: number): number {
35    return this.prefixSum(right) - this.prefixSum(left - 1);
36  }
37  
38  // Build from array
39  static fromArray(arr: number[]): FenwickTree {
40    const tree = new FenwickTree(arr.length);
41    for (let i = 0; i < arr.length; i++) {
42      tree.update(i + 1, arr[i]); // Convert to 1-indexed
43    }
44    return tree;
45  }
46}

Deep Dive

Theoretical Foundation

Fenwick tree stores partial sums in an array using a clever indexing scheme based on binary representation. Each index i is responsible for a range of elements determined by the position of the lowest set bit in i. This allows O(log n) prefix sum queries and updates by traversing ancestors/descendants in the tree structure implicitly stored in the array.

Complexity

Time

Best

O(log n)

Average

O(log n)

Worst

O(log n)

Space

Required

O(n)

Applications

Industry Use

1

Dynamic ranking systems

2

Inversion count in arrays

3

Range sum queries with updates

4

Competitive programming

5

2D range sum queries (2D BIT)

6

Order statistics

7

Fenwick tree on coordinate compression

Use Cases

Range sum queries
Dynamic rankings
Inversion counting
Order statistics

Related Algorithms

AVL Tree (Self-Balancing BST)

A self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. Named after inventors Adelson-Velsky and Landis (1962), AVL trees guarantee O(log n) time for search, insert, and delete operations by maintaining balance through rotations. It was the first self-balancing binary search tree to be invented.

Tree Structures

Segment Tree (Range Query Tree)

Segment Tree is a binary tree data structure for storing intervals/segments that enables efficient range queries (sum, min, max, GCD) and updates in O(log n) time. Each node represents an interval, with leaves representing single elements. Essential for competitive programming, it solves problems like range sum queries with updates, which would be O(n) with arrays but becomes O(log n) with segment trees.

Tree Structures

Lowest Common Ancestor (LCA)

Lowest Common Ancestor (LCA) finds the deepest node that is an ancestor of two given nodes in a tree. This fundamental tree query operation has applications in computational biology (phylogenetic trees), version control systems (finding merge base), network routing, and range queries. Multiple algorithms exist: simple recursive O(n), binary lifting O(log n) per query after O(n log n) preprocessing, and Tarjan's offline algorithm for batch queries.

Tree Structures

Morris Traversal (Threaded Binary Tree)

Morris Traversal is a brilliant tree traversal technique that achieves O(1) space complexity without using recursion or an explicit stack. Invented by Joseph H. Morris in 1979, it temporarily modifies the tree structure by creating 'threads' (temporary links) that allow the algorithm to traverse back to ancestors. After traversal, the original tree structure is restored. This makes it ideal for memory-constrained environments and demonstrates creative problem-solving in algorithm design.

Tree Structures
DSA Explorer

Master Data Structures and Algorithms through interactive visualizations and detailed explanations. Our platform helps you understand complex concepts with clear examples and real-world applications.

Quick Links

  • About DSA Explorer
  • All Algorithms
  • Data Structures
  • Contact Support

Legal

  • Privacy Policy
  • Terms of Service
  • Cookie Policy
  • Code of Conduct

Stay Updated

Subscribe to our newsletter for the latest algorithm explanations, coding challenges, and platform updates.

We respect your privacy. Unsubscribe at any time.

© 2026 Momin Studio. All rights reserved.

SitemapAccessibility
v1.0.0