# knotkit/frequency-table

> Maintains exact counts, prefix sums, range sums, and rank selection over a fixed integer domain

## Use

```ts
import { fenwickFrequencyTable } from 'knotkit/frequency-table'

const counts = fenwickFrequencyTable(10)
counts.add(2, 2)
counts.add(7)
counts.add(9)
counts.count(2) // 2
// Sorted observations are [2, 2, 7, 9].
counts.at(Math.floor((counts.size - 1) / 2)) // 2, the lower median
counts.rangeSum(2, 8) // 3
counts.add(2, -1)
counts.at(-1) // 9, the largest observed key
```

## What it solves

* read the exact number of occurrences of a key
* track repeated integer observations as items enter and leave
* sum frequencies between two bounds after updates
* read a median or quantile by its position among all observations

## Choose a layout

| Factory                               | Choose when                                                                           | Cost                                                                                       |
| ------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| `fenwickFrequencyTable`kind `fenwick` | prefix sums or rank selections repeatedly span many keys between updates              | four bytes per addressable key and one sentinel counter, with at most 2^32 - 1 occurrences |
| `flatFrequencyTable`kind `flat`       | the domain has few keys or the workload primarily updates and reads individual counts | four bytes per addressable key; selection scans from zero to the selected key              |

[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/frequency-table/README.md#performance)

## Try it

Largest table8,19213Reset

* fenwick: prefixSum(8191) = 5, count(0) = 3.
* flat: prefixSum(8191) = 5, count(0) = 3.
* The flat layout scans the prefix. Fenwick sums one partial counter per set bit in the prefix length.

Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/frequency-table/demo.ts) against `knotkit/frequency-table` in your browser; the defaults reproduce the README figure.

## API

| Export                                                                                         | Returns          | Does                                                                       |
| ---------------------------------------------------------------------------------------------- | ---------------- | -------------------------------------------------------------------------- |
| [`fenwickFrequencyTable`](/reference/knotkit/frequency-table/functions/fenwickfrequencytable/) | `FrequencyTable` | Binary indexed tree of exact nonnegative integer frequencies.              |
| [`flatFrequencyTable`](/reference/knotkit/frequency-table/functions/flatfrequencytable/)       | `FrequencyTable` | One unsigned counter per key. Range sums and rank selection scan counters. |

Cost per member. Open a row for every operation.

`fenwickFrequencyTable` 7 members

| Member      | Cost     |
| ----------- | -------- |
| `add`       | O(log C) |
| `prefixSum` | O(log C) |
| `rangeSum`  | O(log C) |
| `at`        | O(log C) |
| `clear`     | O(C)     |
| `size`      | O(1)     |
| `count`     | O(log C) |

`flatFrequencyTable` 7 members

| Member      | Cost               |
| ----------- | ------------------ |
| `add`       | O(1)               |
| `prefixSum` | O(end + 1)         |
| `rangeSum`  | O(end - start + 1) |
| `at`        | O(C)               |
| `clear`     | O(C)               |
| `size`      | O(1)               |
| `count`     | O(1)               |

## Errors

Every error this module throws is `FrequencyTableInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.

* `INVALID_CAPACITY` `INVALID_INDEX` `INVALID_RANGE` `INVALID_DELTA` `COUNT_UNDERFLOW` `COUNT_OVERFLOW`

## When not to use it

| If you need to…                                              | Use instead                                        |
| ------------------------------------------------------------ | -------------------------------------------------- |
| rank keys under a custom comparator or store payloads        | [`knotkit/ordered-map`](/modules/ordered-map/)     |
| membership and set algebra on unique unsigned IDs            | [`knotkit/bitset`](/modules/bitset/)               |
| prefix sums over immutable signed values                     | a prefix-sum array                                 |
| estimate per-key frequencies in a stream with bounded memory | [`knotkit/scalar-sketch`](/modules/scalar-sketch/) |

## Performance

Measured by the suite in [`packages/frequency-table/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/frequency-table/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone. [Compare the recorded timings](/benchmarks/#frequency-table).

## Prompt an agent

Prompt · knotkit/frequency-tableCopy prompt

```
Use knotkit/frequency-table for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/frequency-table'.

Exports:
- `fenwickFrequencyTable` → `FrequencyTable`: Binary indexed tree of exact nonnegative integer frequencies.
- `flatFrequencyTable` → `FrequencyTable`: One unsigned counter per key. Range sums and rank selection scan counters.

Pick the layout by these rules:
- `fenwickFrequencyTable` (kind 'fenwick') when prefix sums or rank selections repeatedly span many keys between updates
- `flatFrequencyTable` (kind 'flat') when the domain has few keys or the workload primarily updates and reads individual counts

Use something else when:
- rank keys under a custom comparator or store payloads → knotkit/ordered-map
- membership and set algebra on unique unsigned IDs → knotkit/bitset
- prefix sums over immutable signed values → a prefix-sum array
- estimate per-key frequencies in a stream with bounded memory → knotkit/scalar-sketch

Errors are FrequencyTableInvalidInputError with a `code` property. Branch on `error.code`, never on the message.

Full page: https://knotkit.jkomyno.dev/modules/frequency-table.md
Types: node_modules/knotkit/frequency-table/ and https://knotkit.jkomyno.dev/reference/knotkit/frequency-table/
```

## See also

* [API reference](/reference/knotkit/frequency-table/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/frequency-table/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/frequency-table/knotkit.capability.json)suggest a change to the source record
