Skip to main content
ProductsDesktop toolsTASTECADDrawing reviewTASTEFILESFile managementTASTEFTPFile transferTASTESSHRemote workspaceTASTEZIPCompression and extractionTASTEWINMFile managementDeveloper toolsTASTECODERust integrated development environmentTASTESTUDIOIntegrated development and test environmentTASTEETLData integration (ETL)ServersTASTEREMOTERemote desktop serverTASTEGEOGeospatial serverTASTEMAILMail workspaceInvestingTASTESTOCKStock auto-trading desktop appGet startedDownloadsDocumentationBuyAll products
Marketplace
News
TechNewsToday's dev newsDeveloper docsProgramming languagesRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp & desktop frameworksTauriFlutterReact NativeElectronAlgorithmsAlgorithm basicsCore algorithmsAdvanced algorithmsPractical algorithms
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcaseCommunity guide
Work with usTech transferWebsite buildDesktop app buildRelease and payment pipelineSales partnerContact
ServicesRemote desktopCustom installer packages
TASTEDEV
Products

Desktop tools

TASTECADComplex drawings, opened with easeTASTEFILESJust the files you need, as fast as possibleTASTEFTPThe tidiest path for your filesTASTESSHA stronger link between you and your serversTASTEZIPPack faster, unpack saferTASTEWINMA keyboard-first file manager with two panes

Developer tools

TASTECODEEdit, build, debug and test Rust apps in one windowTASTESTUDIOFrom editing to remote tests and approved AI fixesTASTEETLMove data while you watch the values

Servers

TASTEREMOTEA remote desktop you run on your own serverTASTEGEORebuilding a GeoServer-compatible geospatial server in RustTASTEMAILTake back control of your email

Investing

TASTESTOCKStock auto-trading that follows the rules you set: when, and what

Get started

DownloadsLatest builds of every productDocsHow to use each productBuySubscriptions and perpetual licencesAll productsEvery product at a glance
All products
MarketplaceNews
Tech

News

Today's dev newsOfficial announcements on languages, frameworks, GitHub and AIDeveloper docsGuides to languages, frameworks and algorithms

Programming languages

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App & desktop frameworksTauriFlutterReact NativeElectron

Algorithms

Algorithm basicsComplexity analysis · Sorting · Searching · Basic data structures · Trees and heapsCore algorithmsGraph traversal · Shortest paths & minimum spanning trees · Dynamic programming · Greedy algorithms · Divide and conquer · BacktrackingAdvanced algorithmsString algorithms · Math and number theory · Bit manipulation · Segment trees · Union-findPractical algorithmsCoding interview strategy · LRU cache · Rate limiting · Consistent hashing
All development docs
Community
ProjectsDiscover builders and their workDevelopment logsDecisions and lessons learnedPromptsReusable instructionsAI tool issuesProblems and workarounds for Claude, Codex, GeminiShowcaseFinished resultsCommunity guideHow we build in the open
Work with us
Tech transferNative apps in Rust and eguiWebsite build10 languages, accounts, docs and downloadsDesktop app buildRust and egui, no WebViewRelease and payment pipelineSigning, MSI, deb, rpm, AppImage, hashesSales partnerRecommend us and earn 30%ContactBuilds, partnerships and investment
Services
Remote desktopReach your computer from a browserCustom installer packagesOnly the features you need, settings preloaded
Buy
EN
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Log in
Log in
TASTEDEV

From small tools to better development.

support@tastedev.netSupport TASTEDEV
ProductsProduct lineupBuyDocsDownloadsMarketplaceSupport
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcase
PoliciesAbout usPrivacy policyTerms of serviceSubscription termsRefund policyCommunity guidelines
AccountLog inSign up
Visitors
Today
Yesterday
Total views
Company
GXSOFT
Representative
CHOI YOUNG GU
Business registration number
853-44-00368
Address
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Phone
+82-10-4404-1523
Email
whitecalvin@tastedev.net
Privacy officer
CHOI YOUNG GU

© 2026 TASTEDEVProduct information is based on verified development sources.Released · improving

Developer docs
Segment trees
Segment treesReference implementationStep-by-step guideOfficial docs and resourcesDiscussionsComments

Other algorithms

Algorithm basics5
Complexity analysisSortingSearchingBasic data structuresTrees and heaps
Core algorithms6
Graph traversalShortest paths & minimum spanning treesDynamic programmingGreedy algorithmsDivide and conquerBacktracking
Advanced algorithms4
String algorithmsMath and number theoryBit manipulationUnion-find
Practical algorithms4
Coding interview strategyLRU cacheRate limitingConsistent hashing

Algorithm

Segment trees

A segment tree answers range sum and minimum queries and applies point updates in O(log n); the Fenwick tree is its lighter cousin for sums.

Start the guideDiscussions

A segment tree is a binary tree that stores a summary, such as a sum, minimum, or maximum, for every range obtained by repeatedly halving an array. The root covers the whole array, each leaf covers a single element, and every internal node combines its two children. Any question about a contiguous range can then be answered by combining a handful of nodes.

Prefix sums answer range sums in O(1) but need O(n) to absorb a single change, while a plain array updates instantly but needs O(n) per query. A segment tree handles both point updates and range queries in O(log n), which makes it the right tool when values keep changing and range questions keep arriving. With lazy propagation it also supports range updates, such as adding a value to an entire range, in O(log n).

Start by understanding where prefix sums fall short, then draw a small tree by hand and trace which nodes a query and an update touch. Next, write the short iterative implementation and a Fenwick tree yourself, and practice on classic problems such as range minimum, counting inversions, and range add with range sum until the patterns feel natural.

On this page

  1. Highlights
  2. Where it is used
  3. Reference implementation
  4. Step-by-step guide
  5. Official docs and resources
  6. Discussions
  7. Comments

Highlights

Summaries of halved ranges

Each node owns one range of the array and stores its sum or minimum; any associative operation with an identity element fits the same structure.

O(log n) updates and queries

Changing an element recomputes one leaf-to-root path, and a range query combines at most two nodes per level.

Range updates with lazy propagation

A range update leaves a note on the nodes that cover it and passes the note to children only when an operation must descend, keeping it O(log n).

A lighter alternative: Fenwick tree

For invertible operations such as sums, a Fenwick tree (BIT) reaches the same complexity with an n + 1 array and a few short loops.

Where it is used

  • Range query problems in coding interviews and contests
  • Leaderboards and cumulative frequency tables
  • Range totals and maxima over time-series metrics
  • Sweep-line geometry and booking systems

Reference implementation

An iterative segment tree: the elements sit in the second half of a 2n array and each earlier slot holds the sum of its two children. update climbs from the leaf to the root recomputing sums, and query climbs from both ends of the half-open range [left, right), adding only the boundary nodes. Running it prints 26, 17, and 28.

segment_tree.py

class SegmentTree:
    """Iterative segment tree: point update and range sum in O(log n)."""

    def __init__(self, values):
        self.n = len(values)
        self.tree = [0] * self.n + list(values)
        for i in range(self.n - 1, 0, -1):
            self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]

    def update(self, index, value):
        i = index + self.n
        self.tree[i] = value
        while i > 1:
            i //= 2
            self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]

    def query(self, left, right):
        """Sum of values[left:right] (half-open range)."""
        total = 0
        lo, hi = left + self.n, right + self.n
        while lo < hi:
            if lo & 1:
                total += self.tree[lo]
                lo += 1
            if hi & 1:
                hi -= 1
                total += self.tree[hi]
            lo //= 2
            hi //= 2
        return total


if __name__ == "__main__":
    tree = SegmentTree([5, 3, 7, 9, 6, 4, 1, 2])
    print(tree.query(2, 6))  # 7 + 9 + 6 + 4 = 26
    tree.update(3, 0)
    print(tree.query(2, 6))  # 7 + 0 + 6 + 4 = 17
    print(tree.query(0, 8))  # 28
python segment_tree.py

Step-by-step guide

Six chapters that take you from installation to the core ideas of Segment trees.

  1. Concepts
  2. How It Works
  3. Implementation
  4. Complexity
  5. Practice Problems
  6. Real-World Use

Official docs and resources

  • OfficialAtCoder Library: Segtree
  • LearnSegment Tree - cp-algorithms
  • LearnFenwick Tree - cp-algorithms
  • LearnVisuAlgo: Segment Tree
  • ReferenceSegment tree (Wikipedia)
  • ReferenceFenwick tree (Wikipedia)
  • ReferencePrefix sum (Wikipedia)
  • CommunityEfficient and easy segment trees (Codeforces)

Discussions

Start a discussion

Ask questions, share experience and trade opinions about Segment trees.

No discussions yet. Start the first one.

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.