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

Segment Tree (Range Query Tree)

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

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.

Prerequisites:
Binary Trees
Recursion
Range queries

Visualization

Interactive visualization for Segment Tree (Range Query Tree)

Interactive visualization with step-by-step execution

Implementation

Language:
1class SegmentTree {
2  private tree: number[];
3  private n: number;
4  
5  constructor(arr: number[]) {
6    this.n = arr.length;
7    this.tree = new Array(4 * this.n).fill(0);
8    this.build(arr, 0, 0, this.n - 1);
9  }
10  
11  private build(arr: number[], node: number, start: number, end: number): void {
12    if (start === end) {
13      this.tree[node] = arr[start];
14      return;
15    }
16    
17    const mid = Math.floor((start + end) / 2);
18    const leftChild = 2 * node + 1;
19    const rightChild = 2 * node + 2;
20    
21    this.build(arr, leftChild, start, mid);
22    this.build(arr, rightChild, mid + 1, end);
23    
24    this.tree[node] = this.tree[leftChild] + this.tree[rightChild];
25  }
26  
27  query(L: number, R: number): number {
28    return this.queryRange(0, 0, this.n - 1, L, R);
29  }
30  
31  private queryRange(node: number, start: number, end: number, L: number, R: number): number {
32    // No overlap
33    if (R < start || L > end) return 0;
34    
35    // Complete overlap
36    if (L <= start && end <= R) return this.tree[node];
37    
38    // Partial overlap
39    const mid = Math.floor((start + end) / 2);
40    const leftSum = this.queryRange(2 * node + 1, start, mid, L, R);
41    const rightSum = this.queryRange(2 * node + 2, mid + 1, end, L, R);
42    
43    return leftSum + rightSum;
44  }
45  
46  update(index: number, value: number): void {
47    this.updateValue(0, 0, this.n - 1, index, value);
48  }
49  
50  private updateValue(node: number, start: number, end: number, index: number, value: number): void {
51    if (start === end) {
52      this.tree[node] = value;
53      return;
54    }
55    
56    const mid = Math.floor((start + end) / 2);
57    if (index <= mid) {
58      this.updateValue(2 * node + 1, start, mid, index, value);
59    } else {
60      this.updateValue(2 * node + 2, mid + 1, end, index, value);
61    }
62    
63    this.tree[node] = this.tree[2 * node + 1] + this.tree[2 * node + 2];
64  }
65}

Deep Dive

Theoretical Foundation

Segment Tree divides array into segments. Each internal node stores aggregate information (sum/min/max) for its segment. Root represents entire array [0,n-1], each child represents half of parent's range. Leaves represent single elements. For range [l,r] query, recursively query relevant segments, combining at most O(log n) nodes. For update, modify path from leaf to root (O(log n) nodes). Space: O(4n). Lazy propagation optimizes range updates from O(n log n) to O(log n).

Complexity

Time

Best

O(log n)

Average

O(log n)

Worst

O(log n)

Space

Required

O(n)

Applications

Industry Use

1

Competitive programming contests

2

Database range queries

3

Computational geometry

4

Graphics rendering (range min/max queries)

5

Stock market analysis (range statistics)

6

Network monitoring (aggregate statistics)

Use Cases

Range queries
Competitive programming
Computational geometry

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

Fenwick Tree (Binary Indexed Tree - BIT)

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).

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