# Binary heap

Implement an in-memory **binary min-heap**: a priority queue of entries, where
an entry is a 64-bit signed integer key (the priority) together with a 64-bit
signed integer value.

This is the classic array-based binary heap (Williams 1964; CLRS chapter 6),
**not** a d-ary heap with more than two children per node, a pairing,
binomial, Fibonacci or leftist heap, a sorted array, or a balanced tree.

## Structure

- **Entry order.** Entries are ordered by key, and entries with equal keys by
  value: `(k1, v1)` is smaller than `(k2, v2)` when `k1 < k2`, or when
  `k1 == k2` and `v1 < v2`. Keys and values are compared as signed 64-bit
  integers. Any `i64` is a valid key and a valid value. The same entry may be
  stored any number of times.
- **An implicit complete binary tree in an array.** A heap of `n` entries
  occupies positions `0 .. n-1` of the tree in level order: position 0 is the
  root, and the children of position `i` are positions `2i + 1` and `2i + 2`.
  There are no gaps: the tree is complete and its last level is filled from
  the left.
- **Heap property.** No entry is smaller than the entry at its parent
  position `(i - 1) / 2`. The smallest entry is therefore at position 0.
- **Storage.** The entries live in one contiguous array, or in two parallel
  arrays (keys and values), that grows as needed. Where position `i` sits in
  that memory is up to you (the array may start at a different index, or be
  padded for alignment), as long as there is a fixed mapping from position to
  memory and no per-entry allocation.
- **Nothing else stores entries.** No second heap, no side index, no buffer of
  pending insertions, no cache of entries.
- The heap is kept in order **only** by moving entries along a path between a
  leaf and the root (sifting up and sifting down), as part of the operations
  below.

These invariants must hold after every operation returns.

## Operations

| Operation | Behaviour |
| --- | --- |
| `new()` | Create an empty heap. |
| `build(keys, values)` | Create a heap that contains the given `m` entries (`keys[i]` with `values[i]`), in `O(m)` time. The inputs are in no particular order and are not modified. |
| `push(key, value)` | Add an entry. |
| `peek() -> entry or absent` | The smallest entry, without removing it. Absent if the heap is empty. |
| `pop() -> entry or absent` | Remove and return the smallest entry. Absent if the heap is empty. |
| `replace(key, value) -> entry or absent` | Remove and return the smallest entry, then add `(key, value)`. The entry returned is the one that was smallest before the new one was added, so it may be larger than the new one. If the heap is empty, just add the entry and report absent. |
| `push_pop(key, value) -> entry` | Add `(key, value)`, then remove and return the smallest entry. The result is the new entry itself when the heap is empty or the new entry is not larger than the heap's smallest entry. |
| `len() -> count` | Number of entries in the heap. |
| `slot(i) -> entry` | The entry at position `i` of the tree (`0 <= i < len()`), as defined above. |

When several entries are equal, it does not matter which of them an operation
returns: they are indistinguishable.

Complexity requirements, for a heap of `n` entries:

- `push`: `O(log n)`, apart from the occasional growth of the array, which
  must be amortised `O(1)` per push.
- `pop`, `replace`, `push_pop`: `O(log n)`. `replace` and `push_pop` must
  each work along a single root-to-leaf path; they are not a `pop` followed
  by a `push`.
- `build`: `O(m)` for `m` entries (not `m` pushes).
- `peek`, `len`, `slot`: `O(1)`. `slot` is used only to check the heap and is
  never timed.

A heap that has been emptied by `pop` must be fully usable again.

## Rules

- Write the heap yourself. Do not use or wrap a heap, priority queue, or
  sorting routine from a library (`std::priority_queue`, `std::push_heap`,
  `std::make_heap`, `BinaryHeap`, `container/heap`, `PriorityQueue`, `heapq`,
  `sort`, ...).
- 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 heap
  has held, and everything is released when the heap 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 heap through ten workloads
   at several sizes up to 100,000 entries, and compares every result
   against a reference. The heap property is checked position by position
   through `slot`.
2. **Speed.** The same ten workloads are then timed on heaps of up to
   3,000,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 binary heap you can write in this language.
