TExcelTAD
Home › Advanced & Succinct Data Structures › Node Copying in O(1) Amortized Overhead

Node Copying in O(1) Amortized Overhead

Fat nodes make every field read a binary search; path copying makes every update copy a whole path. The node-copying method of Driscoll, Sarnak, Sleator and Tarjan (1989) combines the two ideas and gets the best of both for partial persistence:

Theorem (DSST 1989). Any pointer-machine data structure in which every node has in-degree at most a constant pp can be made partially persistent so that each update costs O(1)O(1) amortized extra time and O(1)O(1) amortized extra space per field change, and each field read in any version costs O(1)O(1) worst-case time.

So a red-black tree, whose rebalancing changes O(1)O(1) amortized fields per insertion, becomes a partially persistent search tree with O(1)O(1) amortized space per update and O(lg⁡n)O(\lg n) query time in every version. Sarnak and Tarjan (1986) used exactly this to solve planar point location in O(lg⁡n)O(\lg n) query time and O(n)O(n) space.

The construction

Each node has its ordinary fields, frozen at the version when the node was created, plus

  • 2p2p modification slots, each holding (version, field, new value);
  • back pointers to the nodes that currently point to it (at most pp, since in-degree is at most pp).

Reading field ff of node xx in version vv: start with the frozen value and apply the modifications of ff with version at most vv, in order. At most 2p2p slots, so O(1)O(1).

Writing field ff of node xx (always in the newest version):

  1. If xx has a free modification slot, record (now, f, value) there. Done.
  2. Otherwise xx is full. Create a copy x′x' whose frozen fields are the latest values of xx (with the new value of ff), and empty slots. Fix the back pointers of the nodes x′x' points to. Then every node that points to xx in the newest version must now point to x′x': for each back pointer, write that parent's pointer field, recursively, which may fill and copy the parent, and so on. If xx was a root of the structure, record x′x' as the root of the new version.

Old versions still reach the old xx through their old pointers, and old xx is never modified again, so they are unaffected.

Why the overhead is O(1)O(1) amortized

A write may cascade, copying a chain of nodes, so the worst case is not constant. Use the potential

Φ=c⋅(number of used modification slots in the latest versions of all nodes)\Phi = c \cdot (\text{number of used modification slots in the latest versions of all nodes})

Let one unit of actual work cost at most aa (a slot write, or copying one node of O(1)O(1) fields).

  • A write into a free slot costs aa and raises Φ\Phi by cc: amortized a+ca + c.
  • Copying a full node xx costs aa for the copy, and the old xx stops being "latest", so its 2p2p used slots leave the potential: Φ\Phi drops by 2pc2pc. The copy then causes at most pp writes to parents.

Look at one top-level write as a tree of recursive writes: internal nodes are copies, each with at most pp children, and leaves are slot writes. With kk copies there are at most pk+1pk + 1 leaves, so the amortized cost is at most

k(a−2pc)+(pk+1)(a+c)=k((1+p)a−pc)+a+ck(a - 2pc) + (pk + 1)(a + c) = k\bigl((1 + p)a - pc\bigr) + a + c

With c≥2ac \ge 2a the bracket is at most (1−p)a≤0(1 - p)a \le 0, so every write costs at most a+c=O(1)a + c = O(1) amortized, however long its cascade. The 2p2p slots per node are exactly what pays for the pp parents each copy has to update. Space follows the same argument, since each unit of work creates O(1)O(1) storage.

A partially persistent linked list

The program applies node copying to a sorted singly linked list (in-degree p=1p = 1, so 2 modification slots per node), with a head sentinel whose copies are recorded in a table of roots. It makes 600 insertions, a third of them at the front so that the same nodes are written again and again, and reads back every one of the 601 versions.

python · try it yourself
import bisect, random

MODS = 2                                         # 2p modification slots, p = 1 (in-degree of a list node)

class PNode:
    __slots__ = ("fields", "mods", "back")
    def __init__(self, fields):
        self.fields = dict(fields)               # values at the time the node was created
        self.mods = []                           # (version, field, value), at most MODS
        self.back = set()                        # (latest parent node, its field) pointing here

class NodeCopyingList:
    """Partially persistent sorted linked list by node copying (Driscoll, Sarnak, Sleator, Tarjan)."""
    def __init__(self):
        self.version = 0
        self.roots = [(0, PNode({"key": None, "next": None}))]   # head sentinel per version
        self.copies = self.mod_writes = 0
    def read(self, node, field, v):              # O(MODS) per field read
        val = node.fields[field]
        for ver, f, x in node.mods:
            if f == field and ver <= v: val = x
        return val
    def _latest(self, node, field):
        return self.read(node, field, self.version)
    def _write(self, node, field, value):
        old = self._latest(node, field)
        if len(node.mods) < MODS:                # a free slot: record the change in place
            node.mods.append((self.version, field, value)); self.mod_writes += 1
            if field == "next":
                if old is not None: old.back.discard((node, "next"))
                if value is not None: value.back.add((node, "next"))
            return
        # Full: copy the node with its latest values, then point its parents at the copy.
        self.copies += 1
        latest = {f: self._latest(node, f) for f in node.fields}
        latest[field] = value
        copy = PNode(latest)
        copy.back = set(node.back)
        if field == "next" and old is not None: old.back.discard((node, "next"))
        nxt = latest["next"]
        if nxt is not None:
            nxt.back.discard((node, "next")); nxt.back.add((copy, "next"))
        if self.roots[-1][1] is node:            # the head sentinel: a new root for this version
            self.roots.append((self.version, copy))
        for parent, f in list(copy.back):        # at most p = 1 parent in a list
            self._write(parent, f, copy)         # may cascade upwards
    def head(self, v):
        i = bisect.bisect_right([ver for ver, _ in self.roots], v) - 1
        return self.roots[i][1]
    def insert(self, key):                       # new version: insert key in sorted position
        self.version += 1
        prev = self.head(self.version)
        nxt = self._latest(prev, "next")
        while nxt is not None and self._latest(nxt, "key") < key:
            prev, nxt = nxt, self._latest(nxt, "next")
        node = PNode({"key": key, "next": nxt})
        if nxt is not None: nxt.back.add((node, "next"))
        self._write(prev, "next", node)
    def items(self, v):
        out, x = [], self.read(self.head(v), "next", v)
        while x is not None:
            out.append(self.read(x, "key", v)); x = self.read(x, "next", v)
        return out

rng = random.Random(1989)
lst, ref = NodeCopyingList(), [[]]
worst = 0
for i in range(600):
    k = rng.randrange(100) if i % 3 else 0       # many inserts at the front: repeated writes to the same nodes
    before = lst.copies
    lst.insert(k)
    worst = max(worst, lst.copies - before)
    ref.append(sorted(ref[-1] + [k]))
assert all(lst.items(v) == ref[v] for v in range(601))
print("all 601 versions read back correctly; version 5:", lst.items(5))
print(f"600 updates: {lst.mod_writes} mod writes, {lst.copies} node copies, "
      f"{(lst.mod_writes + lst.copies) / 600:.2f} new pieces of storage per update")
print(f"most copies caused by a single update: {worst}")
all 601 versions read back correctly; version 5: [0, 0, 21, 32, 72]
600 updates: 532 mod writes, 182 node copies, 1.19 new pieces of storage per update
most copies caused by a single update: 2

The total new storage per update stays near one piece (a slot or a copy), and no single update copied more than two nodes. For comparison, path copying would have copied every node on the path from the head to the insertion point, about half the list on average.

In C++

The same method in C++, with the single back pointer of a list node stored in the node. Ten inserts produce ten versions, and the old ones are printed from their own head sentinels.

cpp · try it yourself
#include <cstdio>
#include <memory>
#include <vector>

// Node copying for a partially persistent sorted singly linked list (in-degree p = 1, 2p = 2 mod slots).
struct Node {
    int key;
    Node* next;                          // value of "next" when the node was created
    struct Mod { int version; Node* next; };
    Mod mods[2];
    int nmods = 0;
    Node* parent = nullptr;              // back pointer: the latest node whose next is this one
};

class PersistentList {
    std::vector<std::unique_ptr<Node>> pool;
    std::vector<std::pair<int, Node*>> roots;    // (first version, head sentinel)
    int version = 0;
    Node* make(int key, Node* next) {
        pool.push_back(std::make_unique<Node>(Node{key, next, {}, 0, nullptr}));
        return pool.back().get();
    }
    static Node* next_at(const Node* x, int v) {
        Node* r = x->next;
        for (int i = 0; i < x->nmods; ++i) if (x->mods[i].version <= v) r = x->mods[i].next;
        return r;
    }
    void set_next(Node* x, Node* value) {        // in the newest version
        if (x->nmods < 2) {
            x->mods[x->nmods++] = {version, value};
            if (value) value->parent = x;
            return;
        }
        ++copies;
        Node* c = make(x->key, value);           // copy with the latest field values
        c->parent = x->parent;
        if (value) value->parent = c;
        if (roots.back().second == x) roots.push_back({version, c});
        else set_next(c->parent, c);             // the parent now points to the copy (may cascade)
    }
public:
    long copies = 0;
    PersistentList() { roots.push_back({0, make(-1, nullptr)}); }
    Node* head(int v) const {
        Node* h = roots[0].second;
        for (auto [ver, node] : roots) if (ver <= v) h = node;
        return h;
    }
    void insert(int key) {
        ++version;
        Node* prev = head(version);
        Node* nxt = next_at(prev, version);
        while (nxt && nxt->key < key) { prev = nxt; nxt = next_at(nxt, version); }
        Node* x = make(key, nxt);
        if (nxt) nxt->parent = x;
        x->parent = prev;
        set_next(prev, x);
    }
    void print(int v) const {
        std::printf("version %2d:", v);
        for (Node* x = next_at(head(v), v); x; x = next_at(x, v)) std::printf(" %d", x->key);
        std::printf("\n");
    }
    int versions() const { return version; }
    std::size_t nodes() const { return pool.size(); }
};

int main() {
    PersistentList l;
    for (int k : {50, 10, 40, 10, 30, 20, 60, 10, 45, 5}) l.insert(k);
    for (int v : {0, 1, 3, 6, 10}) l.print(v);
    std::printf("%d versions, %zu nodes allocated (%zu list nodes + head + %ld copies)\n",
                l.versions(), l.nodes(), static_cast<std::size_t>(l.versions()), l.copies);
}
version  0:
version  1: 50
version  3: 10 40 50
version  6: 10 10 20 30 40 50
version 10: 5 10 10 10 20 30 40 45 50 60
10 versions, 13 nodes allocated (10 list nodes + head + 2 copies)

Comparing the three methods

For the same 600 insertions, the program counts the storage each method creates. Path copying has to copy every node before the insertion point, since a singly linked list is one long path, while fat nodes and node copying add O(1)O(1) per insertion.

python · try it yourself
import bisect, random

# The same 600 insertions as above, measured for three persistence methods on a sorted linked list.
rng = random.Random(1989)
keys, fat_pairs, path_nodes, reads_fat = [], 0, 0, 0
for i in range(600):
    k = rng.randrange(100) if i % 3 else 0
    pos = bisect.bisect_right(keys, k)          # insertion point
    keys.insert(pos, k)
    fat_pairs += 2                              # fat nodes: the new node, plus one (version, value) pair
    path_nodes += pos + 1                       # path copying: copy every node before the insertion point
print("storage created by 600 insertions into a persistent sorted list:")
print(f"  fat nodes:     {fat_pairs:6} pieces, but every later read of a field is a binary search")
print(f"  path copying:  {path_nodes:6} nodes ({path_nodes / 600:.1f} per insertion: the whole prefix of the list)")
print(f"  node copying:  {532 + 182 + 600:6} pieces (600 new nodes + 532 slots + 182 copies, from the run above)")
storage created by 600 insertions into a persistent sorted list:
  fat nodes:       1200 pieces, but every later read of a field is a binary search
  path copying:  102411 nodes (170.7 per insertion: the whole prefix of the list)
  node copying:    1314 pieces (600 new nodes + 532 slots + 182 copies, from the run above)

Fat nodes are as small as node copying, but they pay with a binary search on every field read, while node copying reads any field in O(1)O(1).

Beyond partial persistence

Result Overhead Notes
node copying (DSST 1989) O(1)O(1) amortized time and space per change; O(1)O(1) worst-case reads partial persistence, in-degree O(1)O(1)
Brodal (1996) O(1)O(1) worst case per change partial persistence, in-degree O(1)O(1)
node splitting (DSST 1989) O(1)O(1) amortized time and space per change full persistence, in-degree O(1)O(1); versions kept in an order-maintenance structure
fat nodes O(lg⁡m)O(\lg m) per read, O(1)O(1) space per change any structure, partial or full
path copying O(depth)O(\text{depth}) copies per update any tree without parent pointers, full persistence

Full persistence needs a different trick because a node's modifications may come from different branches of the version tree. In node splitting, a full node is split into two nodes, each holding the modifications of a part of the version tree, and versions are compared by their position in a linear order of the version tree maintained with the order-maintenance structure of Dietz and Sleator (1987).

The in-degree condition matters. A structure with unbounded in-degree, such as a node pointed to by many others, would need a copy to update all of its parents. Arrays are not pointer-machine structures at all. Dietz (1989) showed how to make an array fully persistent with O(lg⁡lg⁡n)O(\lg \lg n) time per access using van Emde Boas-style search over versions, and a reduction from predecessor search together with the Pătrașcu-Thorup lower bounds indicates that this cannot be improved in general.

Test yourself

What happens when node copying writes to a node whose modification slots are all used?

  1. The oldest modification is overwritten
  2. The node is copied with its latest values, and every node pointing to it in the newest version is updated to point to the copy, recursively
  3. The write is stored in a fat-node list
  4. The whole structure is copied

In the potential argument, why are 2p2p modification slots enough?

  1. Because each node has at most 2p2p fields
  2. Because copying a full node releases 2p2p units of potential, which pays for the at most pp parent writes it causes
  3. Because there are at most 2p2p versions
  4. Because reads must stay O(lg⁡n)O(\lg n)

Which structures does the DSST node-copying theorem apply to?

  1. Any data structure
  2. Pointer-machine structures whose nodes have in-degree at most a constant
  3. Only arrays
  4. Only balanced binary search trees