Persistent Segment Tree

Path copying: each update clones only the O(log n) nodes on the root-to-leaf path (green) and shares every other subtree by pointer (blue). Old versions stay queryable forever. Second mode walks two versions to find the k-th smallest in a range.

Update: O(log n) Query: O(log n) Pick version: O(1) Mem / version: O(log n) Total: O(n + m log n)
a[ , ] ,  k =
Shared (idle) node
Newly copied (this update path)
Shared with previous version
k-th descent: visited
k-th: answer leaf
n
0
log₂ n
0
Versions
0
Total nodes
0
Nodes copied (last upd)
0
Last result
-

Trace

Load an array to build version 0, then click + New version to watch path copying, or Find k-th to walk two versions down the value axis.

Complexity

OperationTimeNew nodesNote
Build v0O(n)~2nfull tree once
Update → new versionO(log n)⌈log₂n⌉+1only the path is copied
Range query (any version)O(log n)0same as ordinary segtree
Pick / switch versionO(1)0choose a root
K-th smallest in rangeO(log n)0walk version[r] & version[l−1]
Total after m updatesO(n + m log n)vs naive O(n·m)