Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Persistent Data Structures

Keeping every version: path copying, fat nodes and functional lists.

Every Git commit keeps the entire history of a project reachable, yet a new commit stores only what changed: unchanged files and folders are shared with the commits before it. That trick, sharing every part that did not change, works for any linked data structure. Driscoll, Sarnak, Sleator and Tarjan (1989) showed that a pointer structure whose nodes have a bounded number of incoming pointers can keep all its past versions for O(1)O(1) amortized extra time and space per update.

What you’ll learn

  • Distinguish ephemeral, partially, fully and confluently persistent structures by the shape of their version graphs.
  • Make lists and search trees persistent by sharing structure and path copying, and count the space each update costs.
  • Prove that node copying makes any structure of bounded in-degree partially persistent with O(1)O(1) amortized overhead, using a potential function.
  • Answer "what is the kk-th smallest value in a[l..r]a[l..r]?" in O(log⁡n)O(\log n) time with a persistent segment tree.
  • Describe confluent persistence and retroactive data structures, and what remains open about them.

Versions, and the simplest persistent structure

The simplest example is the linked stack. Pushing creates one new node that points to the old top, and popping just returns the second node: neither operation changes an existing node, so every older stack stays intact, and all the versions share their common tails.

python
def push(stack, x):                       # O(1): the new version shares the whole old stack
    return (x, stack)

def pop(stack):                           # O(1): the top, and the version without it
    x, rest = stack
    return x, rest

xs = push(push(push(None, 1), 2), 3)      # 3 -> 2 -> 1
ys = push(xs, 4)                          # 4 -> 3 -> 2 -> 1
zs = push(xs, 5)                          # 5 -> 3 -> 2 -> 1, sharing the nodes of xs with ys
assert ys[1] is xs and zs[1] is xs

Two branches grown from the same version, as full persistence allows, with no copying at all. Changing the bottom element is another matter: every node above it would have to be copied, Θ(n)\Theta(n), because each of them reaches the changed node.

Check your understanding

An editor keeps every state of a document. You may jump back to any earlier state and keep editing from there, which starts a new branch, but you can never merge two branches. Which kind of persistence is this?

  1. Ephemeral
  2. Partial persistence
  3. Full persistence
  4. Confluent persistence
Show the answer

C. Full persistence

Old versions can be updated, which grows a tree of versions: full persistence. Partial persistence would forbid editing old states, and confluent persistence would also allow merging two branches into one.

Path copying

The stack's lesson generalizes. When an update changes a node, every node from which the change can be reached would see a different structure, so those nodes are copied, and everything else is shared. In a tree, the nodes that can reach a node are exactly its ancestors, so an update copies only the path from the root to the changed node: path copying. Each version is identified by its own root.

python
def insert(t, key):                      # t is None or a tuple (left, key, right)
    if t is None:
        return (None, key, None)
    left, k, right = t
    if key < k:
        return (insert(left, key), k, right)     # copy this node; share the right subtree
    if key > k:
        return (left, k, insert(right, key))     # copy this node; share the left subtree
    return t                                     # already present: share everything

versions = [None]
for key in [50, 30, 70, 20, 40, 60, 80, 35]:
    versions.append(insert(versions[-1], key))   # every old root still sees its old tree

Inserting 35 into the tree of 50, 30, 70, 20, 40, 60 and 80 creates exactly 4 nodes: copies of 50, 30 and 40, plus the new 35. All nine versions together use 21 nodes, where storing each version separately would take 36. Tested: every version keeps its own sorted contents.

Path copying is how purely functional languages store their sets, maps and sequences, usually in wide trees: Clojure's persistent vectors and maps branch 32 ways per node, so an update copies about log⁡32n\log_{32} n nodes. Git shares unchanged directories between commits the same way, and databases with multi-version concurrency control keep old versions of rows so that readers see a consistent snapshot while writers proceed.

An early landmark was geometric. To locate a query point in a planar subdivision, Sarnak and Tarjan (1986) swept a vertical line across the plane and kept the segments crossing it in a persistent search tree, one version for each slab between consecutive vertices. A query then searches a single version, in O(log⁡n)O(\log n) time, and with the space-efficient persistence of the next step the whole structure takes only O(n)O(n) space.

Fat nodes and node copying

Path copying costs Θ(depth)\Theta(\text{depth}) space per update even when a single field changes. Two methods do better for partial persistence, where the versions are numbered 1,2,3,…1, 2, 3, \dots in order of time.

Fat nodes. Never copy anything: every field keeps a list of (version, value) pairs, extended on each write. An update then costs O(1)O(1) space, but reading a field in version vv needs a binary search for the last write at or before vv, an O(log⁡m)O(\log m) slowdown on every access after mm updates. The fat-node method saves space and pays in reading time.

Node copying (Driscoll, Sarnak, Sleator & Tarjan, 1989) caps the fat: each node may hold only a constant number of recorded writes, and is copied when it runs out of room.

DerivationProof: node copying, analyzed with a potential function
  1. write(x)  =  {record one modificationif x has room,copy x, then at most p recursive writesif x is full.\text{write}(x) \;=\; \begin{cases} \text{record one modification} & \text{if } x \text{ has room,}\\ \text{copy } x, \text{ then at most } p \text{ recursive writes} & \text{if } x \text{ is full.}\end{cases}

    The construction. Each node keeps its fields as they were when it was created, room for up to 2p2p modifications (field, version, new value), and pointers back to the nodes that point to it in the newest version. Reading a field in version vv scans at most 2p2p modifications for the last one with version at most vv: O(1)O(1). To write a field in the newest version, record a modification if the node has room. If it is full, make a fresh copy holding the newest values and no modifications, write the field there, and then write into each of the at most pp nodes that point to the old node, to redirect them to the copy; those writes may copy their nodes in turn. A node created during the current update has no older version to protect, so later writes to it in the same update simply overwrite its fields; each node is thus copied at most once per update, and the recursion ends.

  2. w^  ≤  c0+c\hat w \;\le\; c_0 + c

    The potential. Let Φ\Phi be cc times the number of modifications stored in the nodes of the newest version, for a constant cc chosen below; Φ\Phi starts at 0 and never goes negative. A write into a node with room has actual cost at most a constant c0c_0 and raises Φ\Phi by cc:

  3. w^  ≤  d  −  2p c  +  p⋅2c  =  d\hat w \;\le\; d \;-\; 2p\,c \;+\; p \cdot 2c \;=\; d

    A write into a full node costs a constant dd for the copy (constant-size nodes, back pointers included), plus the recursive writes. The full node leaves the newest version, taking its 2p2p modifications with it, and the copy starts with none. Assume, by induction on the recursion, that each of the at most pp recursive writes has amortized cost at most 2c2c:

  4. ∑actual costs  ≤  ∑w^  ≤  2c⋅#writes  =  O(#writes)\sum \text{actual costs} \;\le\; \sum \hat w \;\le\; 2c \cdot \#\text{writes} \;=\; O(\#\text{writes})

    Choose c≥max⁡(c0,d/2)c \ge \max(c_0, d/2). Then every write of either kind has amortized cost at most 2c=O(1)2c = O(1), which completes the induction. Since Φ≥0=Φ0\Phi \ge 0 = \Phi_0, the total actual cost is at most the total amortized cost; and the space grows only by modification records and copies, each paid for in the same way:

Full persistence needs one more idea, because the versions now form a tree and "the last write before version vv" is no longer defined by one number. Driscoll et al. lay the version tree out as a list kept in an order-maintenance structure and split full nodes instead of copying them, again with O(1)O(1) amortized overhead per update for bounded in-degree. Brodal (1996) later removed the amortization for partial persistence: O(1)O(1) worst-case time per update. The bound on in-degree is essential: a node pointed to by pp others forces pp writes every time it is copied.

Persistent segment trees: the k-th smallest in a range

A classic contest problem: given a[0..n−1]a[0..n-1], answer many queries "what is the kk-th smallest value in a[l..r]a[l..r]?", with both ends inclusive. Sorting each range costs O(nlog⁡n)O(n \log n) per query; persistence answers each in O(log⁡n)O(\log n).

After coordinate compression the values lie in {0,…,V−1}\{0, \dots, V-1\} with V≤nV \le n. Let version TiT_i be a segment tree over the values that counts how many of a[0..i−1]a[0..i-1] fall into each value range. Ti+1T_{i+1} is TiT_i plus one occurrence of a[i]a[i]: a single root-to-leaf path changes, so path copying builds all n+1n + 1 versions with O(log⁡V)O(\log V) new nodes each. The counts subtract like prefix sums: in any value range, the number of elements of a[l..r]a[l..r] is the count in Tr+1T_{r+1} minus the count in TlT_l. So descend Tr+1T_{r+1} and TlT_l together, going left when the left halves hold at least kk of the range's elements, and otherwise going right with kk reduced by that number.

python
def build_versions(a, V):                  # values in range(V); versions[i] counts a[0..i-1]
    L, R, cnt = [0], [0], [0]              # node 0 is the shared empty tree
    def insert(node, lo, hi, x):           # returns a new node; copies one root-to-leaf path
        L.append(L[node]); R.append(R[node]); cnt.append(cnt[node] + 1)
        new = len(cnt) - 1
        if hi - lo > 1:
            mid = (lo + hi) // 2
            if x < mid:
                L[new] = insert(L[node], lo, mid, x)
            else:
                R[new] = insert(R[node], mid, hi, x)
        return new
    versions = [0]
    for x in a:
        versions.append(insert(versions[-1], 0, V, x))
    return versions, L, R, cnt

def kth_smallest(versions, L, R, cnt, V, l, r, k):   # k-th smallest (1-based) of a[l..r]
    u, v, lo, hi = versions[r + 1], versions[l], 0, V
    while hi - lo > 1:
        mid = (lo + hi) // 2
        left = cnt[L[u]] - cnt[L[v]]              # elements of a[l..r] in [lo, mid)
        if k <= left:
            u, v, hi = L[u], L[v], mid
        else:
            u, v, lo, k = R[u], R[v], mid, k - left
    return lo

O(nlog⁡V)O(n \log V) time and space to build, O(log⁡V)O(\log V) per query; tested against sorting on random arrays. For a=[5,1,4,2,3]a = [5, 1, 4, 2, 3] with V=8V = 8, the five insertions create 5⋅(log⁡28+1)=205 \cdot (\log_2 8 + 1) = 20 nodes, and the 2nd smallest value of a[1..3]=[1,4,2]a[1..3] = [1, 4, 2] is 2.

Confluence, retroactivity and the frontier

Confluent persistence lets an operation combine versions, and that changes the game. Concatenating a one-element list with itself 30 times produces a list of 2302^{30} elements in 30 operations, so a confluently persistent structure must represent objects exponentially larger than the work spent building them, and copying nodes one by one cannot keep up. Fiat and Kaplan (2001) gave general transformations for confluent persistence, later improved by Collette, Iacono and Langerman (2012), and Demaine, Langerman and Price (2008) built confluently persistent tries as a model of version control with merges.

Retroactive data structures (Demaine, Iacono & Langerman, 2004; journal version 2007) go further: they let you insert or delete an operation in the past and see how the present changes, as when a late transaction must be backdated. A partially retroactive structure answers queries only about the present; a fully retroactive one answers queries about any time. In general, a change made rr operations in the past can cost Ω(r)\Omega(r) time to propagate, so no generic transformation is efficient, but specific structures do far better: a partially retroactive priority queue runs in O(log⁡n)O(\log n) time per operation.

Key takeaways

  • Partial persistence keeps a line of versions, full persistence a tree (old versions can be updated), and confluent persistence a directed acyclic graph (versions can be combined); immutable structures are fully persistent for free.
  • Path copying copies only the nodes from which a change can be reached: O(1)O(1) for a stack push, O(log⁡n)O(\log n) per update in a balanced tree, with each version identified by its root.
  • Fat nodes cost O(1)O(1) space per update but slow every read by a search; node copying, analyzed with a potential function, gives O(1)O(1) amortized time and space per update and O(1)O(1) access for structures of bounded in-degree (Driscoll, Sarnak, Sleator & Tarjan, 1989).
  • A persistent segment tree of prefix versions answers "the kk-th smallest value in a[l..r]a[l..r]" in O(log⁡n)O(\log n) time by descending Tr+1T_{r+1} and TlT_l together.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A persistent red-black tree with nn keys uses path copying. About how many new nodes does one insertion create?

  1. O(1)O(1)
  2. O(log⁡n)O(\log n)
  3. O(n)O(n)
  4. O(nlog⁡n)O(n \log n)
Show the answer

B. O(log⁡n)O(\log n)

Only the nodes that can reach the change, the ancestors of the new key, must be copied, plus O(1)O(1) neighbors touched by rotations: O(log⁡n)O(\log n) nodes, since the tree's height is O(log⁡n)O(\log n). Everything else is shared with the previous version.

Question 2

Why does the node-copying method require the in-degree of every node to be bounded by a constant pp?

  1. Because reading a field must scan all the pointers into its node
  2. Because copying a full node forces a write into every node that points to it, and 2p2p free modification slots per node are what pay for those writes
  3. Because nodes with many incoming pointers cannot be stored in memory
  4. Because the potential function counts incoming pointers
Show the answer

B. Because copying a full node forces a write into every node that points to it, and 2p2p free modification slots per node are what pay for those writes

When a node is copied, its predecessors must be redirected to the copy, one write each. The potential stored in the 2p2p modifications that the old node takes out of the newest version pays for at most pp such writes at amortized cost 2c2c each. With unbounded in-degree, one copy could trigger arbitrarily many writes.

Question 3

Version TiT_i of a persistent segment tree counts the values of a[0..i−1]a[0..i-1]. To find the kk-th smallest value of a[l..r]a[l..r] (both ends inclusive), which two versions does the query descend together, subtracting their counts?

  1. TrT_r and TlT_l
  2. Tr+1T_{r+1} and Tl−1T_{l-1}
  3. Tr+1T_{r+1} and TlT_l
  4. TrT_r and Tl−1T_{l-1}
Show the answer

C. Tr+1T_{r+1} and TlT_l

Tr+1T_{r+1} counts a[0..r]a[0..r] and TlT_l counts a[0..l−1]a[0..l-1], so their difference counts exactly a[l..r]a[l..r], the same convention as prefix sums: P[r+1]−P[l]P[r+1] - P[l].

Question 4

What is the main drawback of the fat-node method for partial persistence?

  1. Each update copies the whole path from the root
  2. It works only for trees
  3. Old versions eventually become unreadable
  4. Reading a field requires searching its history of writes, an O(log⁡m)O(\log m) slowdown on every access after mm updates
Show the answer

D. Reading a field requires searching its history of writes, an O(log⁡m)O(\log m) slowdown on every access after mm updates

A fat node stores every write to every field, so updates cost O(1)O(1) space, but each read must find the last write at or before the requested version. Node copying caps the history at 2p2p writes per node, which makes reads O(1)O(1).

Further reading

  • J. R. Driscoll, N. Sarnak, D. D. Sleator & R. E. Tarjan, "Making data structures persistent," Journal of Computer and System Sciences 38(1) (1989), 86–124.
  • N. Sarnak & R. E. Tarjan, "Planar point location using persistent search trees," Communications of the ACM 29(7) (1986), 669–679.
  • C. Okasaki, Purely Functional Data Structures (Cambridge University Press, 1998).
  • E. D. Demaine, J. Iacono & S. Langerman, "Retroactive data structures," ACM Transactions on Algorithms 3(2) (2007).
  • E. D. Demaine, MIT 6.851 Advanced Data Structures, lecture notes on persistent and retroactive data structures (Spring 2012).