{"post":{"slug":"what-is-a-segment-tree-2026","title":"What Is a Segment Tree? 2026 Guide","excerpt":"A segment tree answers range questions over an array — sum, min, max — in logarithmic time, and lets you update an element without rebuilding anything. Here is how it is built and when it is overkill.","category":"code","date":"July 20, 2026","author":"ByteLedger Team","content":"<span class=\"dropcap\">A</span> segment tree is a binary tree built over an array so that any range query — sum, minimum, maximum, or a similar aggregate over a subrange — can be answered in O(log n) time, and any single-element update only touches O(log n) nodes to stay correct. It exists for one situation: an array that changes over time, where you also need fast answers to range-aggregate queries. It sits alongside [union-find](/blog/what-is-union-find-2026) as one of the classic structures for problems that mix queries with updates.\n\n## What changed in 2026\n\n- **It remains a deliberately old, deliberately stable idea.** The core structure has not needed to change — this is a case where a decades-old design is still the right default for the problem it solves.\n- **Iterative, array-based implementations are now the common default.** Recursive pointer-based segment trees are easier to explain, but most production code now builds the tree as a flat array for better cache behavior.\n- **Persistent variants show up more in real systems.** Versioned range queries borrow segment tree ideas, and that pattern has spread from competitive programming into production analytics code.\n\n## How a segment tree is built\n\nEach leaf represents one array element. Each internal node represents the aggregate (sum, min, whatever operation you chose) of its two children, recursively, all the way up to a root that represents the aggregate of the entire array. Building it is a single recursive pass:\n\n```python\ndef build(arr, tree, node, start, end):\n    if start == end:\n        tree[node] = arr[start]\n        return\n    mid = (start + end) // 2\n    build(arr, tree, 2 * node, start, mid)\n    build(arr, tree, 2 * node + 1, mid + 1, end)\n    tree[node] = tree[2 * node] + tree[2 * node + 1]  # combine step\n```\n\nThe combine step on the last line is the only part that changes for min, max, or gcd instead of sum.\n\n## Range queries in O(log n)\n\nA query for range [L, R] walks the tree and only descends into a subtree that partially overlaps the requested range. Subtrees fully inside return their precomputed aggregate immediately; subtrees fully outside return a neutral value (zero for sum, infinity for min). Because the tree has height O(log n), the whole query stays O(log n) instead of scanning the array.\n\n## Updates without a rebuild\n\nChanging one array element means updating that leaf and then walking back up, recomputing each ancestor's aggregate from its two children. That is O(log n) nodes touched, never the whole tree.\n\n## How it compares to the alternatives\n\n| Structure | Range query | Point update | Range update | Best for |\n| --- | --- | --- | --- | --- |\n| Plain array | O(n) | O(1) | O(n) | Small or rarely-queried data |\n| Prefix sum array | O(1) | O(n) to fix all sums | O(n) | Static data, no updates after setup |\n| Fenwick tree (BIT) | O(log n) | O(log n) | O(log n) with a trick | Sum-like invertible operations, simpler code |\n| Segment tree | O(log n) | O(log n) | O(log n) with lazy propagation | Min/max/gcd or anything non-invertible |\n\nIf the only operation you need is sum, a Fenwick tree does the same job with less code. Reach for a full segment tree when you need range minimum, maximum, or an operation that cannot be undone by subtraction.\n\n## Lazy propagation for range updates\n\nUpdating every element in a range one at a time defeats the purpose of a fast structure. Lazy propagation fixes this by marking a subtree as \"pending an update\" without pushing it down to its children immediately — the push only happens the next time that subtree is visited. This keeps range updates at O(log n) instead of O(n).\n\n## Common mistakes\n\n**Reaching for a segment tree before checking if the data ever changes.** If it does not, a prefix-sum array answers the same queries in O(1) with far less code.\n\n**Using a segment tree for sum only, ignoring the simpler Fenwick tree.** Both hit O(log n), but the Fenwick tree is shorter and easier to get right under pressure.\n\n**Forgetting lazy propagation and updating ranges element by element.** This silently turns an O(log n) operation back into an O(n) one, often only surfacing once inputs get large.\n\n## FAQ\n\n**Is a segment tree the same as a binary search tree?**\nNo. A binary search tree orders elements by value for fast lookup. A segment tree is organized by array position, not value, and is built for range aggregates.\n\n**When should I use a Fenwick tree instead?**\nWhen the operation is invertible, like sum, and you want less code with the same O(log n) guarantees. Fenwick trees do not naturally support min or max.\n\n**Does a segment tree need the array size to be a power of two?**\nNo, though some simple array-based implementations size the underlying array generously to make the indexing math cleaner. It works correctly for any size.\n\n**Is a segment tree worth building for a one-off script?**\nRarely. It pays off when there are many interleaved queries and updates. For a single pass over static data, simpler structures are faster to write and just as fast to run.\n\n## Where to go next\n\n- [What is union-find in 2026](/blog/what-is-union-find-2026)\n- [What is a directed acyclic graph in 2026](/blog/what-is-a-directed-acyclic-graph-2026)\n- [What is topological sort in 2026](/blog/what-is-topological-sort-2026)","hue":280,"metaTitle":"Segment Tree Explained 2026","metaDescription":"What is a segment tree in 2026? A clear guide to range queries, point and range updates, lazy propagation, and how it compares to prefix sums and Fenwick trees.","keywords":["segment tree 2026","segment tree data structure","range query algorithm","segment tree vs fenwick tree","lazy propagation segment tree","range sum query","segment tree python","binary indexed tree comparison","competitive programming data structures"],"tldr":["**It answers range questions fast** — sum, min, max, or gcd over any subrange of an array in O(log n) instead of O(n).","**Updates stay cheap too** — changing one element only touches O(log n) nodes, not the whole array or a full rebuild.","**It generalizes further than a Fenwick tree** — segment trees handle non-invertible operations like min and max; Fenwick trees are limited to invertible ones like sum.","**Lazy propagation extends it to range updates** — updating an entire subrange at once without individually touching every element in it.","**Skip:** building a segment tree when a plain prefix-sum array would do — if the data never changes after queries start, prefix sums are simpler and cheaper to set up."],"readTime":"4 min read","wordCount":905},"related":[{"slug":"what-is-union-find-2026","title":"What Is Union-Find? 2026 Guide","excerpt":"Union-find is a data structure built for one question: are these two things in the same group. Here is how it answers that almost instantly, and why the naive version is nowhere near fast enough.","category":"code","date":"July 24, 2026","author":"ByteLedger Team","readTime":"4 min read","hue":290},{"slug":"what-is-a-b-tree-database-2026","title":"What Is a B-Tree in 2026? Why Databases Use Them","excerpt":"A B-tree is a wide, shallow multi-way tree built to minimize disk reads. Here is why databases and filesystems use it instead of a binary search tree.","category":"code","date":"July 17, 2026","author":"ByteLedger Team","readTime":"4 min read","hue":150},{"slug":"what-is-a-binary-tree-2026","title":"What is a binary tree in 2026? The data structure explained","excerpt":"A binary tree is a structure where each node has at most two children. Here is what that means, how it works, and why it shows up everywhere in software.","category":"code","date":"May 25, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":195}],"sameCategory":[{"slug":"bazel-build-explained-2026","title":"Bazel Explained: What Hermetic Builds Actually Cost","excerpt":"Bazel delivers reproducible, precisely cached builds and demands that you describe everything. Here is what you get, what it costs, and who should say no.","category":"code","date":"August 19, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":145},{"slug":"graphql-federation-2026","title":"GraphQL Federation: One Graph, Many Teams","excerpt":"Federation composes independently-owned subgraphs into a single API. Here is what it solves, the operational cost it adds, and when a simpler gateway is enough.","category":"code","date":"August 19, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":300},{"slug":"hermetic-builds-explained-2026","title":"Hermetic Builds Explained: Same Inputs, Same Output","excerpt":"A hermetic build depends only on declared inputs. Here is what that property gives you, the common leaks that break it, and how to move toward it incrementally.","category":"code","date":"August 19, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":130},{"slug":"monorepo-tooling-compared-2026","title":"Monorepo Tooling Compared: What You Actually Need","excerpt":"Monorepo tools solve task orchestration and caching, not repository layout. Here is what each tier provides and how to tell when you have outgrown the simple option.","category":"code","date":"August 19, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":150}],"newer":{"slug":"what-is-a-seed-file-database-2026","title":"What is a seed file in a database? The 2026 guide","excerpt":"A seed file is the script that loads known, reusable data into a database after the schema exists. Here is what belongs in one and how it differs from a migration.","category":"code","date":"July 20, 2026","author":"ByteLedger Team","readTime":"4 min read","hue":200},"older":{"slug":"what-is-a-simple-ira-vs-sep-ira-2026","title":"SIMPLE IRA vs SEP IRA in 2026: which fits your business","excerpt":"Both are employer-sponsored retirement plans with less paperwork than a 401(k), but they differ sharply on contribution limits and who has to contribute. Here is the 2026 comparison.","category":"finance","date":"July 20, 2026","author":"ByteLedger Team","readTime":"4 min read","hue":38}}