# Skip list

Implement an in-memory **skip list**: an ordered map from 64-bit signed
integer keys to 64-bit signed integer values.

This is the classic randomized skip list (William Pugh, "Skip Lists: A
Probabilistic Alternative to Balanced Trees", 1990), **not** a balanced
tree, a deterministic skip list (1-2-3 skip list), a B-tree, a sorted array,
or a linked list with a separate index structure or hash table.

## Structure

- **One node per entry.** Each node holds exactly one key and its value. Each
  key is stored exactly once, in the node that represents it; a list of `n`
  entries has exactly `n` nodes.
- **Every node has a tower** of forward links. A node of height `h` (`h >= 1`)
  has `h` forward links, one for each of levels `0` to `h - 1`, and it
  appears in exactly those levels.
- **Every level is a sorted singly linked list.** Level `L` links, in
  ascending key order, exactly the nodes whose height is greater than `L`.
  Level 0 therefore links all nodes in ascending key order. A node's link at
  level `L` points to the next node (in key order) whose height is greater
  than `L`, or is null if there is none.
- **A header** holds the first link of every level. It is not an entry.
- **Tower heights are random.** When a key is inserted that was not present,
  the new node's height is drawn from a geometric distribution: it starts at
  1, and each further level is added with a fixed probability `p`, until a
  level is not added or a fixed maximum height is reached. `p` and the
  maximum height are your choice, within these limits:
  - `1/8 <= p <= 1/2` (`1/2` and `1/4` are the usual choices);
  - the maximum height is at most 64 and large enough for at least 2^32
    entries, that is `(1/p)^max >= 2^32` (for example 32 levels for
    `p = 1/2`, 16 for `p = 1/4`).
- **The random numbers come from a pseudo-random generator that you write
  yourself** (for example xorshift, splitmix or a PCG step) and that each
  list seeds with a fixed constant when it is created, so that runs are
  reproducible. Do not use a library random number generator, the clock,
  system entropy, memory addresses, or anything else as a source of
  randomness. Every height is drawn from the generator alone: it does not
  depend on the key, on the number of entries, on the current height of the
  list, or on the other towers (apart from the cap at the maximum height).
- **A node's height never changes** after it is inserted. Replacing the value
  of a key that is present keeps its node and its tower. Towers are never
  rebuilt, rebalanced, raised or lowered.
- **Removal really removes.** `remove` unlinks the node from every level it
  appears in before it returns. There are no deleted markers or lazily
  removed entries.
- A node holds its key, its value, its forward links (and its height, if you
  want it). It holds no other links: no backward links at any level. `range`
  only ever moves forward.
- The skip list is the only structure that stores entries. No side index,
  hash table, sorted array, or cache of entries or lookups.
- Keys are unique. Keys are compared as signed 64-bit integers; any `i64`
  value is a valid key and any `i64` value is a valid value.

These invariants must hold after every operation returns.

## Operations

| Operation | Behaviour |
| --- | --- |
| `new()` | Create an empty list. |
| `insert(key, value) -> bool` | If `key` is absent, add the entry and return `true`. If `key` is present, replace its value and return `false`. |
| `get(key) -> value or absent` | Return the value stored for `key`, or report that the key is absent. |
| `remove(key) -> bool` | If `key` is present, delete its entry and return `true`. Otherwise change nothing and return `false`. |
| `range(lo, hi, limit) -> entries` | Produce the entries with `lo <= key <= hi` (both bounds inclusive) in ascending key order, stopping after `limit` entries. If `lo > hi` or `limit` is 0 the result is empty. `lo` and `hi` need not be keys in the list. |
| `len() -> count` | Number of entries in the list. |
| `height() -> levels` | Number of levels in use: the height of the tallest node in the list, 0 for an empty list. |
| `level_count(level) -> count` | Number of nodes whose tower reaches level `level` (nodes of height greater than `level`). `level_count(0)` equals `len()`; for any `level >= height()` the result is 0. `level` can be any non-negative integer. |

Complexity requirements, for a list of `n` entries (expected, over the
random tower heights):

- `insert`, `get`, `remove`: expected `O(log n)`.
- `range`: expected `O(log n + m)` where `m` is the number of entries
  produced. It must search down through the levels for the first key
  `>= lo` and then walk level 0; it must not be built from repeated `get`s
  or from a scan that starts at the smallest key.
- `len`: `O(1)`.
- `height`: may take `O(n)`.
- `level_count(level)`: should take time proportional to the number of nodes
  it counts (walk the list of that level).
- `height` and `level_count` are used only to check the list and are never
  timed.

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

## Rules

- Write the skip list yourself. Do not use or wrap an ordered container,
  tree, sorted map, or skip list from a library (`std::map`, `BTreeMap`,
  `TreeMap`, `ConcurrentSkipListMap`, `sortedcontainers`, ...), and do not
  use a library random number generator (`rand()`, `<random>`, `math/rand`,
  `java.util.Random`, `Math.random`, Python's `random`, ...).
- 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, bit operations, and similar.
- Memory use must stay proportional to the largest number of entries the list
  has held, and everything is released when the list 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 list through ten workloads
   at several sizes up to 50,000 entries, and compares every result
   against a reference. Tower heights are random, so `height()` and
   `level_count()` are not compared with the reference; instead the driver
   checks that they describe a skip list with geometrically distributed
   heights. For a list of `len` entries:
   - `height()` is 0 when `len` is 0, and otherwise between
     `max(1, floor(floor(log2(len)) / 4))` and 64;
   - `level_count(0) == len`, `level_count` never grows from one level to
     the next, `level_count(height() - 1) >= 1` and
     `level_count(height()) == 0`;
   - when `len >= 4096`, between `len / 16` and `0.8 * len` nodes reach
     level 1.

   A correct list with any allowed `p` passes these checks with
   overwhelming probability (each fails less than once in 10^9 runs); a list
   with degenerate towers (all of height 1, all of the maximum height, or
   heights that barely vary) does not.
2. **Speed.** The same ten workloads are then timed on a list of 1,250,000
   entries, 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 skip list you can write in this language.
