# Radix tree

Implement an in-memory **radix tree**: a path-compressed trie over bytes
that maps byte-string keys to 64-bit signed integer values, and answers
prefix queries: the longest stored key that is a prefix of a given string,
the number of keys that start with a prefix, and the values of those keys in
key order.

This is the classic radix tree, also called a compact or compressed trie
(Morrison's PATRICIA, generalised to branching on whole bytes; Knuth, The Art
of Computer Programming, volume 3, section 6.3), **not** a hash map of whole
keys, a sorted array, list or search tree of whole keys, a trie with one byte
per node (no path compression), a ternary search tree, a burst trie, a trie
that branches on bits instead of bytes, or any structure that hashes keys or
prefixes.

## Keys and values

- A **key** is a string of 0 to 255 bytes. Any byte value (0x00 to 0xFF) may
  occur anywhere in a key. The empty key is a valid key. One key may be a
  prefix of another (`"ab"` and `"abc"` may both be stored).
- Keys are unique. A **value** is any 64-bit signed integer.
- **Key order** is lexicographic order on unsigned bytes: compare the first
  byte where two keys differ, as a number from 0 to 255; if one key is a
  proper prefix of the other, the shorter key comes first. (So `""` <
  `"a"` < `"ab"` < `"b"`, and `0x7F` < `0x80` < `0xFF`.)
- Every key or prefix passed to an operation is at most 255 bytes long. It
  is passed as a view of bytes owned by the caller, valid only for the
  duration of the call; the caller reuses that memory afterwards. **The tree
  must copy every byte it keeps.**

## Structure

- **Nodes and labels.** The tree is a rooted tree of nodes. Every node except
  the root is reached from its parent through an edge that carries a
  non-empty *label* of one or more bytes. A node *represents* the string
  spelled by the labels on the path from the root to it; the root represents
  the empty string. The root always exists, also in an empty tree.
- **Branching on bytes.** The labels of the edges leaving a node start with
  pairwise different bytes, so a node has at most 256 children, and the
  child to follow for the next byte of a key is unique.
- **Keys live at their nodes.** Each stored key has a node that represents it,
  and that node holds the key's value (the empty key is held by the root).
  The key's bytes exist in the tree only as the labels on its path.
- **Path compression, kept in both directions.** Every node other than the
  root holds a key, or has at least two children, or both. So `insert`
  splits an edge only where the new key leaves an existing label (or ends
  inside it), and `remove` deletes a node that is left with no key and no
  children, and merges a node that is left with no key and exactly one child
  into that child (concatenating the two labels). The root is never removed
  or merged; it may have any number of children, including one.
- It follows that the shape of the tree is fully determined by its set of
  keys: its nodes are exactly the root, one node for each stored key, and one
  node for each string `s` such that two stored keys both extend `s` and
  continue with different bytes after it.
- **Subtree counts.** Every node knows how many keys are stored in its
  subtree (itself included), so that `prefix_count` does not have to walk the
  subtree. These counts are kept up to date by `insert` and `remove`.
- How a node finds the child for a byte is up to you: for example a sorted
  array of first bytes searched linearly or by binary search, small arrays
  that grow into a 256-entry table, or a 256-bit bitmap with a popcount
  index. It must not use hashing. How labels are stored is up to you as well
  (inside the node, in a separate allocation, as a reference into a copy of a
  key that the tree owns, ...), as long as each node's label is available to
  it directly, without a search.
- **Nothing else stores keys or values.** No side index, hash table, sorted
  array, linked list of keys in order, cache of lookups, or second copy of
  the entries. `prefix_values` produces its answer by walking the tree.
- **Removal really removes.** `remove` restores the structure above before it
  returns. There are no deleted markers or lazily removed entries.

These invariants must hold after every operation returns.

Example: after inserting `romane`, `romanus`, `romulus`, `rubens`, `ruber`,
`rubicon` and `rubicundus`, the tree has 14 nodes:

```
(root)
 └ r
    ├ om
    │  ├ an
    │  │  ├ e          romane
    │  │  └ us         romanus
    │  └ ulus          romulus
    └ ub
       ├ e
       │  ├ ns         rubens
       │  └ r          ruber
       └ ic
          ├ on         rubicon
          └ undus      rubicundus
```

Its height is 4. Inserting `rom` changes neither (the node for `rom`
exists already and now holds a key); inserting `ro` then splits the edge
`om` into `o` and `m` (15 nodes, height 5). Removing `romulus` and then `rom`
leaves the node for `rom` without a key and with one child, so it is merged
with that child, whose label becomes `man` (13 nodes, height 4).

## Operations

| Operation | Behaviour |
| --- | --- |
| `new()` | Create an empty tree. |
| `insert(key, value) -> bool` | If `key` is absent, add it with `value` and return `true`. If it is present, replace its value and return `false`. |
| `get(key) -> value or absent` | The value stored for `key`, or absent. |
| `remove(key) -> bool` | If `key` is present, delete it and return `true`. Otherwise change nothing and return `false`. |
| `longest_prefix(key) -> (length, value) or absent` | Of all stored keys that are a prefix of `key` (`key` itself and the empty key included), the longest one: return its length in bytes and its value. Absent if no stored key is a prefix of `key`. |
| `prefix_count(prefix) -> count` | The number of stored keys that start with `prefix` (`prefix` itself included, if it is stored). `prefix_count("")` is `len()`. |
| `prefix_values(prefix, out_values, limit) -> count` | Write the values of the stored keys that start with `prefix` to `out_values`, in key order, stopping after `limit` values, and return the number written. With `limit` 0, or when no key starts with `prefix`, nothing is written and the result is 0. The buffer holds at least `limit` values. |
| `len() -> count` | Number of keys in the tree. |
| `node_count() -> count` | The number of nodes of the tree as defined under Structure, the root included: 1 for an empty tree. |
| `height() -> edges` | The largest number of edges on a path from the root down to a node: 0 when the root has no children, 1 when every key has one edge on its path, and so on. |

`prefix` arguments need not be keys, and need not end at a node: a prefix
that ends inside a label selects the subtree below that edge.

`node_count()` and `height()` describe the tree defined under Structure.
Since that tree is determined by the set of keys, every correct
implementation returns the same numbers, whatever its internal layout; if
your representation has other objects (for example separate leaf records, or
no node object for the root), count as defined above, not your objects.

Complexity requirements, for a tree of `n` keys and a key or prefix of `m`
bytes. A step from a node to its child for a given byte must take time
independent of `n` (a node has at most 256 children).

- `get`, `longest_prefix`: `O(m)`: one walk down from the root.
- `insert`, `remove`: `O(m)`, plus copying at most one label (when an edge
  is split or two labels are merged), plus the occasional growth of a
  node's child array.
- `prefix_count`: `O(m)`, using the subtree counts. It must not visit the
  keys it counts.
- `prefix_values`: `O(m)` to find where the prefix ends, then a walk that
  visits only the nodes on the paths to the values it produces and the
  nodes that it passes on the way. It must not be built from repeated
  `get`s, and must not collect more values than it returns or sort them.
- `len`: `O(1)`.
- `node_count`, `height`: may take `O(n)`. They are used only to check the
  tree and are never timed.

A tree that has been emptied by `remove` must be fully usable again
(`len() == 0`, `node_count() == 1`, `height() == 0`, and later inserts work).

## Rules

- Write the radix tree yourself. Do not use or wrap a map, set, trie,
  hash table, sorted container or sorting routine from a library
  (`std::map`, `std::unordered_map`, `HashMap`, `BTreeMap`, `TreeMap`,
  `Dictionary`, `dict`, `Map`, `sort`, ...), not even for the children of a
  node. Plain growable arrays (`std::vector`, `Vec`, `ArrayList`, `list`,
  ...) used as arrays are fine.
- Use only the language's standard library. No third-party packages and no
  code in another language (no C extensions, FFI, JNI, cgo, or inline assembly).
- No architecture-specific SIMD intrinsics (`<arm_neon.h>`, `std::arch`,
  `System.Runtime.Intrinsics`, and the like). Portable features of the
  language and its compiler are fine: branch hints, prefetch hints, and
  portable vector types.
- Single-threaded: do not start threads or processes.
- Do not change process-wide runtime settings (garbage collector tuning,
  JIT flags, recursion limits, allocator replacement, and so on).
- Low-level utilities from the standard library are fine: arrays, block
  copies, byte-string comparison (`memcmp` and the like), searching an array
  for a byte or a value (linear or binary search), bit operations, and
  similar.
- Memory use must stay proportional to the largest number of keys plus the
  largest total length of keys that the tree has held, and everything is
  released when the tree is destroyed in languages with manual memory
  management.
- Language features that trade safety for speed (for example `unsafe` in
  Rust) are permitted.

The exact names, signatures, and file names for your language are given in
the language binding that accompanies this specification. The benchmark
driver calls exactly that interface.

## How it is judged

1. **Correctness.** A fixed test suite drives the tree through ten workloads
   at several sizes up to 100,000 keys, and compares every result against a
   reference: lookups, longest prefixes, prefix counts, every value in key
   order, and keys with 0x00 and 0xFF bytes, the empty key, and keys of 255
   bytes. `node_count()` and `height()` are compared with the exact values
   that the tree defined under Structure has, including after keys are
   inserted and removed again.
2. **Speed.** The same ten workloads are then timed on a tree of 1,500,000
   keys (path-like keys of 2 to about 40 bytes, 17 on average, with long
   shared prefixes at several depths), which is far larger than the CPU
   caches. Only the time spent inside your operations is measured, so write
   for performance: the goal is the fastest correct radix tree you can write
   in this language.
