### Why I Built This: The Story Behind Nibble Trie↵
↵
Every competitive programmer knows the frustration of designing a solid algorithm, only to hit a **TLE** or **MLE** wall because of the container used to store frequencies or states.↵
↵
While solving heavy problems involving **forced-online queries** (CF 1771F) and **runtime-generated keys** like prefix sums and XOR paths (CF 877F, CF 1006F), standard tools kept falling short:↵
↵
* **Arrays (`int freq[MAX_A]`):** Give instant $O(1)$ access, but trigger **MLE** once keys reach $10^9$ or $10^{18}$.↵
↵
* **Coordinate Compression:** Solves large ranges in $O(N \log N)$, but fails completely when queries are **forced online** or keys are generated dynamically.↵
↵
* **`std::map`:** Handles arbitrary keys dynamically, but its $O(\log N)$ pointer-chasing penalty causes **TLE** under tight time limits.↵
↵
* **`std::unordered_map`:** Offers average $O(1)$ speed, but relies on hashing—making it vulnerable to deterministic **anti-hash tests**.↵
↵
I asked myself: *Why choose between a 1-level direct array (fast, but uses gigabytes) and a 64-level Binary Trie (memory-efficient, but too deep and cache-unfriendly)?*↵
↵
Slicing an integer **4 bits (one hex digit / a nibble)** at a time instead of 1 bit shrinks tree height by $4\times$. By separating internal pointer arrays (`void*[16]`) from the bottom leaf data array (`T[16]`), I designed and implemented the **Nibble Trie**—a custom Radix-16 sparse array providing **deterministic $O(1)$** access without hashing.↵
↵
> **Video Walkthrough (Arabic):** Prefer a step-by-step video explanation? Watch the full walkthrough on YouTube **[here](https://youtu.be/XXMVETSH9Eg?si=DSUaTQ75lf4bzjlG)**.↵
↵
---↵
↵
### 1. Core Idea: Treating Numbers as Base-16 Words↵
↵
Why does a normal array fail on large keys? Because it treats a number like $x = 305,419,896$ as a single giant index, forcing us to allocate memory for every unused number between $0$ and $x$.↵
↵
Instead of viewing an integer as one flat index, the **Nibble Trie** views its binary representation as a **fixed-length sequence of 4-bit chunks**:↵
↵
* In computer architecture, **4 bits** is called a **Nibble**, which represents one hexadecimal digit (`0` to `F`, or $0$ to $15$).↵
↵
* A 32-bit integer is simply an **8-digit Base-16 word** (each digit between $0$ and $15$).↵
↵
* A 64-bit integer is simply a **16-digit Base-16 word**.↵
↵
Just like a standard string Trie builds a word character-by-character, a Nibble Trie builds a number **nibble-by-nibble** from its Most Significant Bits (MSB) down to its Least Significant Bits (LSB).↵
↵
**How Bit-Slicing Extracts Each Level:**↵
↵
At any depth with bit offset `shift`, we isolate the next 4-bit chunk using two bitwise operations:↵
↵
$$\text{nibble} = (x \gg \text{shift}) \ \& \ 15$$↵
↵
1. **Right Shift (`x >> shift`):** Slides the target 4 bits all the way to the rightmost positions (`[3..0]`).↵
↵
2. **Bitwise AND (`& 15`):** Since $15 = 1111_2$, this mask zeroes out everything except those bottom 4 bits, giving a clean index in $[0, 15]$.↵
↵
---↵
↵
### 2. Building a Number Level by Level & Prefix Sharing↵
↵
↵
↵
When you access or insert a number $x$, you are walking down `LEVELS` layers—narrowing down the exact location of $x$ by a factor of $16$ at every step:↵
↵
* **Level 0 (Root):** Reads the highest 4 bits, splitting the entire number range into $16$ giant buckets.↵
↵
* **Level 1:** Reads the next 4 bits, splitting that bucket into $16$ smaller sub-buckets, and so on.↵
↵
* **Prefix Sharing (Why It Saves Memory):** Suppose you insert $x_1 = \text{0x12345678}$ and $x_2 = \text{0x12349ABC}$. Because their top four nibbles (`1, 2, 3, 4`) are identical, both numbers walk through the **exact same nodes** across Levels $0, 1, 2,$ and $3$. They only branch into separate arrays at Level $4$ (`5` vs `9`). Any unvisited branch remains `nullptr` and costs zero memory.↵
↵
**Two-Tier Node Separation (Routing vs. Storage):**↵
↵
A naive implementation would make every level an array of pointers, adding an extra layer at the bottom just to hold values. Instead, the Nibble Trie splits the tree into two distinct tiers:↵
↵
1. **Internal Levels (`0` to `LEVELS - 2`):** Arrays of 16 pointers (`void*[16]`) whose only job is routing to the next level.↵
↵
2. **Leaf Level (`LEVELS - 1`):** Arrays of 16 actual values (`T[16]`) stored contiguously in memory, accessed directly by the lowest 4 bits (`x & 15`). This eliminates an entire layer of pointers and saves one heap allocation per key.↵
↵
**Concrete Step-by-Step Trace (`x = 0x12345678`, `LEVELS = 8`):**↵
↵
Tracing $x = 305,419,896_{10} = \text{0x12345678}_{16}$ splits it cleanly into 8 nibbles:↵
↵
* **Depth 0 (Root) — Bits `[31..28]`:** `(x >> 28) & 15 = 1` $\rightarrow$ `root[1]` points to Depth 1 (`void*[16]`).↵
↵
* **Depth 1 — Bits `[27..24]`:** `(x >> 24) & 15 = 2` $\rightarrow$ `curr[2]` points to Depth 2 (`void*[16]`).↵
↵
* **Depth 2 — Bits `[23..20]`:** `(x >> 20) & 15 = 3` $\rightarrow$ `curr[3]` points to Depth 3 (`void*[16]`).↵
↵
* **Depth 3 — Bits `[19..16]`:** `(x >> 16) & 15 = 4` $\rightarrow$ `curr[4]` points to Depth 4 (`void*[16]`).↵
↵
* **Depth 4 — Bits `[15..12]`:** `(x >> 12) & 15 = 5` $\rightarrow$ `curr[5]` points to Depth 5 (`void*[16]`).↵
↵
* **Depth 5 — Bits `[11..8]`:** `(x >> 8) & 15 = 6` $\rightarrow$ `curr[6]` points to Depth 6 (`void*[16]`).↵
↵
* **Depth 6 (`LEVELS - 2`) — Bits `[7..4]`:** `(x >> 4) & 15 = 7` $\rightarrow$ `curr[7]` points to **Leaf (`T[16]`)**.↵
↵
* **Depth 7 (`LEVELS - 1`) — Bits `[3..0]`:** `x & 15 = 8` $\rightarrow$ Direct index `leaf[8]` accesses value `T`.↵
↵
---↵
↵
### 3. When to Use It (and When Not To)↵
↵
**Ideal Use Cases:**↵
↵
* **Forced Online Queries:** Problems encrypted with `last_ans` (e.g., CF 1771F) where offline compression is impossible.↵
↵
* **Runtime-Generated Keys:** Prefix sums, tree/grid XOR paths, and Meet-in-the-Middle states (CF 877F, CF 1006F, CF 1709E).↵
↵
* **Anti-Hash Safety:** Deterministic $O(1)$ performance with zero collision risk and no need for `splitmix64`.↵
↵
**When to Avoid It:**↵
↵
* **Offline Heavy Random Access:** In offline algorithms doing $10^8+$ random updates (like 3D Mo's in CF 940F), offline coordinate compression with a flat 1D array stays inside CPU L1 Cache and runs faster than any pointer-based tree.↵
↵
---↵
↵
### 4. Time & Space Complexity Proof↵
↵
For keys fitting in $W$ bits (maximum value $K_{\max}$), the tree height $D$ depends only on $W$, **not** on the element count $N$:↵
↵
$$D = \left\lceil \frac{W}{4} \right\rceil = \left\lceil \log_{16}(K_{\max} + 1) \right\rceil$$↵
↵
* **Time Complexity:** $O(D) = O(W / 4) = O(1)$ per operation.↵
↵
* **Space Complexity:** $O(N \cdot W / 4)$ words worst-case for insertions; $O(0)$ heap allocation for read-only `query()`.↵
↵
<spoiler summary="Detailed Hardware Latency & Byte-Level Memory Calculations">↵
↵
**Hardware Latency Model:**↵
↵
$$\text{Total Execution Time} \approx Q \times D \times T_{\text{hop}}$$↵
↵
where $Q$ is the query count and $T_{\text{hop}}$ is pointer latency ($\approx 1\text{ ns}$ in L1/L2 cache, or $\approx 25\text{ ns}$ on RAM misses).↵
↵
1. **Standard $O(N \log N)$ Workload ($N = 2 \cdot 10^5$, $D = 8$):** Executes $\approx 2.8 \cdot 10^7$ hops, finishing in **under $0.15\text{s}$**.↵
↵
2. **Extreme $O(N^{5/3})$ Workload ($Q \approx 2 \cdot 10^8$ random ops, $D = 8$):** Out-of-cache hops take $2 \cdot 10^8 \times 25\text{ ns} = 5.0\text{s}$, setting the practical ceiling around $4 \cdot 10^7$ random ops/sec.↵
↵
**Exact Byte-Level Memory Model (64-bit OS + 16B allocator header):**↵
↵
* **Internal Node (`void*[16]`):** $16 \times 8 + 16 = 144\text{ bytes}$.↵
↵
* **Leaf Node (`T[16]`):** $16 \times \text{sizeof}(T) + 16$ ($80\text{ bytes}$ for `T = int`).↵
↵
$$\text{Memory}_{\text{worst}} = \left( \sum_{d=0}^{D-2} \min(16^d, N) \right) \times 144 + \min(16^{D-1}, N) \times (16 \cdot \text{sizeof}(T) + 16)$$↵
↵
1. **32-bit Keys ($D = 8$, `T = int`, $N = 2 \cdot 10^5$):** Upper levels ($d = 0 \dots 4$) take $10.1\text{ MB}$, levels $5\text{--}6$ take $57.6\text{ MB}$, and leaves take $16.0\text{ MB}$ $\rightarrow$ **$83.7\text{ MB}$ total**.↵
↵
2. **60-bit Keys in Meet-in-the-Middle (CF 1006F, $D = 15$):**↵
* **Symmetric Split ($N = 2^{19}$ stored):** Requires **$731.5\text{ MB}$** (triggers 256 MB MLE).↵
* **Asymmetric Split ($N = 2^{16}$ stored, $2^{22}$ `query()`):** Cuts peak RAM to **$100.2\text{ MB}$** while `query()` allocates $0\text{ bytes}$.↵
↵
</spoiler>↵
↵
---↵
↵
### 5. My C++ Implementation↵
↵
```cpp↵
template <typename T = int, int LEVELS = 8>↵
struct Nibble_Trie {↵
// Bit offset of the top 4-bit nibble (e.g., 28 for 32-bit)↵
static constexpr int START_SHIFT = (LEVELS - 1) * 4;↵
void *root[16] = {nullptr};↵
↵
// Recursively free nodes (children before parent)↵
void clear_node(void **curr, int depth) {↵
for (int i = 0; i < 16; i++) {↵
if (!curr[i]) continue;↵
if (depth == LEVELS - 2) {↵
delete[] static_cast<T *>(curr[i]);↵
} else {↵
clear_node(static_cast<void **>(curr[i]), depth + 1);↵
delete[] static_cast<void **>(curr[i]);↵
}↵
curr[i] = nullptr;↵
}↵
}↵
↵
void clear() { clear_node(root, 0); }↵
~Nibble_Trie() { clear(); }↵
↵
// Access or lazily allocate path for x in O(LEVELS)↵
inline T &operator[](unsigned long long x) {↵
void **curr = root;↵
for (int shift = START_SHIFT; shift >= 8; shift -= 4) {↵
unsigned int idx = (x >> shift) & 15;↵
if (!curr[idx]) curr[idx] = new void *[16]();↵
curr = static_cast<void **>(curr[idx]);↵
}↵
unsigned int leaf_dir = (x >> 4) & 15;↵
if (!curr[leaf_dir]) curr[leaf_dir] = new T[16]();↵
return static_cast<T *>(curr[leaf_dir])[x & 15];↵
}↵
↵
// Read-only lookup in O(LEVELS) with zero heap allocation↵
inline T query(unsigned long long x) const {↵
void *const *curr = root;↵
for (int shift = START_SHIFT; shift >= 8; shift -= 4) {↵
unsigned int idx = (x >> shift) & 15;↵
if (!curr[idx]) return T{};↵
curr = static_cast<void *const *>(curr[idx]);↵
}↵
unsigned int leaf_dir = (x >> 4) & 15;↵
if (!curr[leaf_dir]) return T{};↵
return static_cast<const T *>(curr[leaf_dir])[x & 15];↵
}↵
};↵
```↵
↵
---↵
↵
### 6. Part-by-Part Code Walkthrough↵
↵
**A. Template Parameters & `START_SHIFT`**↵
↵
* `T` defines the value type (`int`, `long long`, etc.), and `LEVELS` sets the height ($4 \times \text{LEVELS}$ bits).↵
↵
* For 32-bit keys (`LEVELS = 8`), `START_SHIFT` evaluates at compile time to $(8 - 1) \times 4 = 28$, isolating bits `[31..28]` first.↵
↵
**B. Why `void*` and `static_cast`?**↵
↵
* **`void*`:** Holds a raw memory address so `root[16]` and internal arrays can point to either another `void*[16]` pointer array or a `T[16]` leaf array.↵
↵
* **`static_cast`:** Tells the compiler the exact element stride at **compile time** (8 bytes for `void*` vs. `sizeof(T)` for leaves) with **zero runtime overhead**.↵
↵
**C. Write & Lazy Allocation (`operator[]`)**↵
↵
* The loop steps `shift` down to `8`, extracting `(x >> shift) & 15` and allocating `new void *[16]()` only on `nullptr`.↵
↵
* At `shift = 4` (`depth = LEVELS - 2`), it allocates the leaf array `new T[16]()` and indexes the lowest 4 bits via `[x & 15]`.↵
↵
**D. Read-Only Lookup (`query`)**↵
↵
* Unlike `operator[]`, `query(x)` returns `T{}` immediately upon hitting any `nullptr`, guaranteeing $O(0)$ memory allocation when querying absent keys.↵
↵
**E. Recursive Cleanup (`clear_node`)**↵
↵
* At `depth == LEVELS - 2`, child pointers `curr[i]` point directly to leaf arrays (`T[16]`), so they are deleted via `delete[] static_cast<T *>(curr[i])` without deeper recursion.↵
↵
---↵
↵
### 7. Dynamic Depth Scaling & Optimization Rules↵
↵
Scale `LEVELS` to match your problem's exact constraint ceiling (`ceil(bits / 4)`):↵
↵
* **Up to $4 \cdot 10^9$ (32-bit):** `LEVELS = 8`, `START_SHIFT = 28` — Standard array values ($A_i \le 10^9$).↵
↵
* **Up to $4.5 \cdot 10^{15}$ (52-bit):** `LEVELS = 13`, `START_SHIFT = 48` — Prefix sums up to $10^{14}$.↵
↵
* **Up to $1.15 \cdot 10^{18}$ (60-bit):** `LEVELS = 15`, `START_SHIFT = 56` — Grid/tree XOR paths up to $10^{18}$.↵
↵
* **Up to $1.8 \cdot 10^{19}$ (64-bit):** `LEVELS = 16`, `START_SHIFT = 60` — Full `uint64_t` keys or Zobrist hashes.↵
↵
**Three Contest Optimization Rules:**↵
↵
1. **Tighten `LEVELS`:** Never default to 16 levels unless keys truly use all 64 bits; shaving off unnecessary levels cuts millions of pointer hops.↵
↵
2. **Asymmetric Meet-in-the-Middle:** Insert fewer states with `operator[]` and perform more lookups with zero-allocation `query()`.↵
↵
3. **Use `_exit(0)` on Single-Testcase Tasks:** When allocating $10^5+$ nodes, `cout.flush(); _exit(0);` skips destructor teardown time and lets the OS reclaim memory in bulk.↵
↵
---↵
↵
### 8. Battle-Tested Practice Problems↵
↵
I validated the **Nibble Trie** across **15 problems**: 10 medium problems for practicing `LEVELS` tuning and bit-packing, and 5 heavy stress-test problems.↵
↵
**Part 1: Medium & Warm-Up Problems (10 Problems)**↵
↵
1. **[CF 702B — Powers of Two](https://codeforces.me/problemset/problem/702/B)** (`LEVELS = 8`) ↵
32-bit frequency counting ($a_i \le 10^9$) to find pairs summing to $2^k$.↵
↵
2. **[CF 1598C — Delete Two Elements](https://codeforces.me/problemset/problem/1598/C)** (`LEVELS = 8`) ↵
Two-sum frequency lookups over $a_i \le 10^9$ using zero-allocation `query()`.↵
↵
3. **[CF 1790D — Matryoshkas](https://codeforces.me/problemset/problem/1790/D)** (`LEVELS = 8`) ↵
Sparse frequency map over doll sizes up to $10^9$.↵
↵
4. **[CF 977F — Consecutive Subsequence](https://codeforces.me/problemset/problem/977/F)** (`LEVELS = 8`) ↵
Dynamic programming transitions indexed directly by array values $a_i \le 10^9$.↵
↵
5. **[CF 1915E — Romantic Glasses](https://codeforces.me/problemset/problem/1915/E)** (`LEVELS = 13`) ↵
Shifted alternating prefix sums up to $2 \cdot 10^{14}$ stored as 52-bit keys.↵
↵
6. **[CF 1426D — Non-zero Segments](https://codeforces.me/problemset/problem/1426/D)** (`LEVELS = 13`) ↵
Tracking visited prefix sums up to $2 \cdot 10^{14}$ using `Nibble_Trie<bool, 13>`.↵
↵
7. **[CF 1931D — Divisible Pairs](https://codeforces.me/problemset/problem/1931/D)** (`LEVELS = 15`) ↵
Packing remainder pairs `(a[i] % x, a[i] % y)` into a 60-bit key `(uint64_t(r1) << 30) | r2`.↵
↵
8. **[CF 1974C — Beautiful Triple Pairs](https://codeforces.me/problemset/problem/1974/C)** (`LEVELS = 15`) ↵
Packing 20-bit triples ($a_i \le 10^6$) into 60-bit keys to count near-matching triplets.↵
↵
9. **[CF 651C — Watchmen](https://codeforces.me/problemset/problem/651/C)** (`LEVELS = 16`) ↵
Packing 2D coordinates ($|x_i|, |y_i| \le 10^9$) into 62-bit keys `((uint64_t(x + 1e9)) << 31) | uint64_t(y + 1e9)`.↵
↵
10. **[CF 1133D — Zero Quantity Maximization](https://codeforces.me/problemset/problem/1133/D)** (`LEVELS = 16`) ↵
Packing reduced slope fractions $(p, q)$ into 62-bit keys to avoid floating-point precision loss.↵
↵
**Part 2: Heavy Stress-Test Problems (5 Problems)**↵
↵
11. **[CF 1771F — Hossam and Range Minimum Query](https://codeforces.me/problemset/problem/1771/F)** (`LEVELS = 8`) ↵
Forced-online queries immune to anti-hash hacks where coordinate compression is impossible.↵
↵
12. **[CF 877F — Ann and Books](https://codeforces.me/problemset/problem/877/F)** (`LEVELS = 13`) ↵
Mo's algorithm with runtime-generated prefix sums up to $10^{14}$; tests `query()` zero-allocation speed.↵
↵
13. **[CF 1006F — Xor-Paths](https://codeforces.me/problemset/problem/1006/F)** (`LEVELS = 15`) ↵
60-bit XOR Meet-in-the-Middle using an asymmetric split to keep memory under 256 MB.↵
↵
14. **[CF 1709E — XOR Tree](https://codeforces.me/problemset/problem/1709/E)** (`LEVELS = 8`) ↵
Small-to-large merging on trees; stresses rapid trie creation and cleanup (`clear()`).↵
↵
15. **[CF 1418G — Three Occurrences](https://codeforces.me/problemset/problem/1418/G)** (`LEVELS = 16`) ↵
Sliding-window frequency tracking over 64-bit Zobrist hashes ($N \le 5 \cdot 10^5$) with zero collision risk.
↵
Every competitive programmer knows the frustration of designing a solid algorithm, only to hit a **TLE** or **MLE** wall because of the container used to store frequencies or states.↵
↵
While solving heavy problems involving **forced-online queries** (CF 1771F) and **runtime-generated keys** like prefix sums and XOR paths (CF 877F, CF 1006F), standard tools kept falling short:↵
↵
* **Arrays (`int freq[MAX_A]`):** Give instant $O(1)$ access, but trigger **MLE** once keys reach $10^9$ or $10^{18}$.↵
↵
* **Coordinate Compression:** Solves large ranges in $O(N \log N)$, but fails completely when queries are **forced online** or keys are generated dynamically.↵
↵
* **`std::map`:** Handles arbitrary keys dynamically, but its $O(\log N)$ pointer-chasing penalty causes **TLE** under tight time limits.↵
↵
* **`std::unordered_map`:** Offers average $O(1)$ speed, but relies on hashing—making it vulnerable to deterministic **anti-hash tests**.↵
↵
I asked myself: *Why choose between a 1-level direct array (fast, but uses gigabytes) and a 64-level Binary Trie (memory-efficient, but too deep and cache-unfriendly)?*↵
↵
Slicing an integer **4 bits (one hex digit / a nibble)** at a time instead of 1 bit shrinks tree height by $4\times$. By separating internal pointer arrays (`void*[16]`) from the bottom leaf data array (`T[16]`), I designed and implemented the **Nibble Trie**—a custom Radix-16 sparse array providing **deterministic $O(1)$** access without hashing.↵
↵
> **Video Walkthrough (Arabic):** Prefer a step-by-step video explanation? Watch the full walkthrough on YouTube **[here](https://youtu.be/XXMVETSH9Eg?si=DSUaTQ75lf4bzjlG)**.↵
↵
---↵
↵
### 1. Core Idea: Treating Numbers as Base-16 Words↵
↵
Why does a normal array fail on large keys? Because it treats a number like $x = 305,419,896$ as a single giant index, forcing us to allocate memory for every unused number between $0$ and $x$.↵
↵
Instead of viewing an integer as one flat index, the **Nibble Trie** views its binary representation as a **fixed-length sequence of 4-bit chunks**:↵
↵
* In computer architecture, **4 bits** is called a **Nibble**, which represents one hexadecimal digit (`0` to `F`, or $0$ to $15$).↵
↵
* A 32-bit integer is simply an **8-digit Base-16 word** (each digit between $0$ and $15$).↵
↵
* A 64-bit integer is simply a **16-digit Base-16 word**.↵
↵
Just like a standard string Trie builds a word character-by-character, a Nibble Trie builds a number **nibble-by-nibble** from its Most Significant Bits (MSB) down to its Least Significant Bits (LSB).↵
↵
**How Bit-Slicing Extracts Each Level:**↵
↵
At any depth with bit offset `shift`, we isolate the next 4-bit chunk using two bitwise operations:↵
↵
$$\text{nibble} = (x \gg \text{shift}) \ \& \ 15$$↵
↵
1. **Right Shift (`x >> shift`):** Slides the target 4 bits all the way to the rightmost positions (`[3..0]`).↵
↵
2. **Bitwise AND (`& 15`):** Since $15 = 1111_2$, this mask zeroes out everything except those bottom 4 bits, giving a clean index in $[0, 15]$.↵
↵
---↵
↵
### 2. Building a Number Level by Level & Prefix Sharing↵
↵
↵
↵
When you access or insert a number $x$, you are walking down `LEVELS` layers—narrowing down the exact location of $x$ by a factor of $16$ at every step:↵
↵
* **Level 0 (Root):** Reads the highest 4 bits, splitting the entire number range into $16$ giant buckets.↵
↵
* **Level 1:** Reads the next 4 bits, splitting that bucket into $16$ smaller sub-buckets, and so on.↵
↵
* **Prefix Sharing (Why It Saves Memory):** Suppose you insert $x_1 = \text{0x12345678}$ and $x_2 = \text{0x12349ABC}$. Because their top four nibbles (`1, 2, 3, 4`) are identical, both numbers walk through the **exact same nodes** across Levels $0, 1, 2,$ and $3$. They only branch into separate arrays at Level $4$ (`5` vs `9`). Any unvisited branch remains `nullptr` and costs zero memory.↵
↵
**Two-Tier Node Separation (Routing vs. Storage):**↵
↵
A naive implementation would make every level an array of pointers, adding an extra layer at the bottom just to hold values. Instead, the Nibble Trie splits the tree into two distinct tiers:↵
↵
1. **Internal Levels (`0` to `LEVELS - 2`):** Arrays of 16 pointers (`void*[16]`) whose only job is routing to the next level.↵
↵
2. **Leaf Level (`LEVELS - 1`):** Arrays of 16 actual values (`T[16]`) stored contiguously in memory, accessed directly by the lowest 4 bits (`x & 15`). This eliminates an entire layer of pointers and saves one heap allocation per key.↵
↵
**Concrete Step-by-Step Trace (`x = 0x12345678`, `LEVELS = 8`):**↵
↵
Tracing $x = 305,419,896_{10} = \text{0x12345678}_{16}$ splits it cleanly into 8 nibbles:↵
↵
* **Depth 0 (Root) — Bits `[31..28]`:** `(x >> 28) & 15 = 1` $\rightarrow$ `root[1]` points to Depth 1 (`void*[16]`).↵
↵
* **Depth 1 — Bits `[27..24]`:** `(x >> 24) & 15 = 2` $\rightarrow$ `curr[2]` points to Depth 2 (`void*[16]`).↵
↵
* **Depth 2 — Bits `[23..20]`:** `(x >> 20) & 15 = 3` $\rightarrow$ `curr[3]` points to Depth 3 (`void*[16]`).↵
↵
* **Depth 3 — Bits `[19..16]`:** `(x >> 16) & 15 = 4` $\rightarrow$ `curr[4]` points to Depth 4 (`void*[16]`).↵
↵
* **Depth 4 — Bits `[15..12]`:** `(x >> 12) & 15 = 5` $\rightarrow$ `curr[5]` points to Depth 5 (`void*[16]`).↵
↵
* **Depth 5 — Bits `[11..8]`:** `(x >> 8) & 15 = 6` $\rightarrow$ `curr[6]` points to Depth 6 (`void*[16]`).↵
↵
* **Depth 6 (`LEVELS - 2`) — Bits `[7..4]`:** `(x >> 4) & 15 = 7` $\rightarrow$ `curr[7]` points to **Leaf (`T[16]`)**.↵
↵
* **Depth 7 (`LEVELS - 1`) — Bits `[3..0]`:** `x & 15 = 8` $\rightarrow$ Direct index `leaf[8]` accesses value `T`.↵
↵
---↵
↵
### 3. When to Use It (and When Not To)↵
↵
**Ideal Use Cases:**↵
↵
* **Forced Online Queries:** Problems encrypted with `last_ans` (e.g., CF 1771F) where offline compression is impossible.↵
↵
* **Runtime-Generated Keys:** Prefix sums, tree/grid XOR paths, and Meet-in-the-Middle states (CF 877F, CF 1006F, CF 1709E).↵
↵
* **Anti-Hash Safety:** Deterministic $O(1)$ performance with zero collision risk and no need for `splitmix64`.↵
↵
**When to Avoid It:**↵
↵
* **Offline Heavy Random Access:** In offline algorithms doing $10^8+$ random updates (like 3D Mo's in CF 940F), offline coordinate compression with a flat 1D array stays inside CPU L1 Cache and runs faster than any pointer-based tree.↵
↵
---↵
↵
### 4. Time & Space Complexity Proof↵
↵
For keys fitting in $W$ bits (maximum value $K_{\max}$), the tree height $D$ depends only on $W$, **not** on the element count $N$:↵
↵
$$D = \left\lceil \frac{W}{4} \right\rceil = \left\lceil \log_{16}(K_{\max} + 1) \right\rceil$$↵
↵
* **Time Complexity:** $O(D) = O(W / 4) = O(1)$ per operation.↵
↵
* **Space Complexity:** $O(N \cdot W / 4)$ words worst-case for insertions; $O(0)$ heap allocation for read-only `query()`.↵
↵
<spoiler summary="Detailed Hardware Latency & Byte-Level Memory Calculations">↵
↵
**Hardware Latency Model:**↵
↵
$$\text{Total Execution Time} \approx Q \times D \times T_{\text{hop}}$$↵
↵
where $Q$ is the query count and $T_{\text{hop}}$ is pointer latency ($\approx 1\text{ ns}$ in L1/L2 cache, or $\approx 25\text{ ns}$ on RAM misses).↵
↵
1. **Standard $O(N \log N)$ Workload ($N = 2 \cdot 10^5$, $D = 8$):** Executes $\approx 2.8 \cdot 10^7$ hops, finishing in **under $0.15\text{s}$**.↵
↵
2. **Extreme $O(N^{5/3})$ Workload ($Q \approx 2 \cdot 10^8$ random ops, $D = 8$):** Out-of-cache hops take $2 \cdot 10^8 \times 25\text{ ns} = 5.0\text{s}$, setting the practical ceiling around $4 \cdot 10^7$ random ops/sec.↵
↵
**Exact Byte-Level Memory Model (64-bit OS + 16B allocator header):**↵
↵
* **Internal Node (`void*[16]`):** $16 \times 8 + 16 = 144\text{ bytes}$.↵
↵
* **Leaf Node (`T[16]`):** $16 \times \text{sizeof}(T) + 16$ ($80\text{ bytes}$ for `T = int`).↵
↵
$$\text{Memory}_{\text{worst}} = \left( \sum_{d=0}^{D-2} \min(16^d, N) \right) \times 144 + \min(16^{D-1}, N) \times (16 \cdot \text{sizeof}(T) + 16)$$↵
↵
1. **32-bit Keys ($D = 8$, `T = int`, $N = 2 \cdot 10^5$):** Upper levels ($d = 0 \dots 4$) take $10.1\text{ MB}$, levels $5\text{--}6$ take $57.6\text{ MB}$, and leaves take $16.0\text{ MB}$ $\rightarrow$ **$83.7\text{ MB}$ total**.↵
↵
2. **60-bit Keys in Meet-in-the-Middle (CF 1006F, $D = 15$):**↵
* **Symmetric Split ($N = 2^{19}$ stored):** Requires **$731.5\text{ MB}$** (triggers 256 MB MLE).↵
* **Asymmetric Split ($N = 2^{16}$ stored, $2^{22}$ `query()`):** Cuts peak RAM to **$100.2\text{ MB}$** while `query()` allocates $0\text{ bytes}$.↵
↵
</spoiler>↵
↵
---↵
↵
### 5. My C++ Implementation↵
↵
```cpp↵
template <typename T = int, int LEVELS = 8>↵
struct Nibble_Trie {↵
// Bit offset of the top 4-bit nibble (e.g., 28 for 32-bit)↵
static constexpr int START_SHIFT = (LEVELS - 1) * 4;↵
void *root[16] = {nullptr};↵
↵
// Recursively free nodes (children before parent)↵
void clear_node(void **curr, int depth) {↵
for (int i = 0; i < 16; i++) {↵
if (!curr[i]) continue;↵
if (depth == LEVELS - 2) {↵
delete[] static_cast<T *>(curr[i]);↵
} else {↵
clear_node(static_cast<void **>(curr[i]), depth + 1);↵
delete[] static_cast<void **>(curr[i]);↵
}↵
curr[i] = nullptr;↵
}↵
}↵
↵
void clear() { clear_node(root, 0); }↵
~Nibble_Trie() { clear(); }↵
↵
// Access or lazily allocate path for x in O(LEVELS)↵
inline T &operator[](unsigned long long x) {↵
void **curr = root;↵
for (int shift = START_SHIFT; shift >= 8; shift -= 4) {↵
unsigned int idx = (x >> shift) & 15;↵
if (!curr[idx]) curr[idx] = new void *[16]();↵
curr = static_cast<void **>(curr[idx]);↵
}↵
unsigned int leaf_dir = (x >> 4) & 15;↵
if (!curr[leaf_dir]) curr[leaf_dir] = new T[16]();↵
return static_cast<T *>(curr[leaf_dir])[x & 15];↵
}↵
↵
// Read-only lookup in O(LEVELS) with zero heap allocation↵
inline T query(unsigned long long x) const {↵
void *const *curr = root;↵
for (int shift = START_SHIFT; shift >= 8; shift -= 4) {↵
unsigned int idx = (x >> shift) & 15;↵
if (!curr[idx]) return T{};↵
curr = static_cast<void *const *>(curr[idx]);↵
}↵
unsigned int leaf_dir = (x >> 4) & 15;↵
if (!curr[leaf_dir]) return T{};↵
return static_cast<const T *>(curr[leaf_dir])[x & 15];↵
}↵
};↵
```↵
↵
---↵
↵
### 6. Part-by-Part Code Walkthrough↵
↵
**A. Template Parameters & `START_SHIFT`**↵
↵
* `T` defines the value type (`int`, `long long`, etc.), and `LEVELS` sets the height ($4 \times \text{LEVELS}$ bits).↵
↵
* For 32-bit keys (`LEVELS = 8`), `START_SHIFT` evaluates at compile time to $(8 - 1) \times 4 = 28$, isolating bits `[31..28]` first.↵
↵
**B. Why `void*` and `static_cast`?**↵
↵
* **`void*`:** Holds a raw memory address so `root[16]` and internal arrays can point to either another `void*[16]` pointer array or a `T[16]` leaf array.↵
↵
* **`static_cast`:** Tells the compiler the exact element stride at **compile time** (8 bytes for `void*` vs. `sizeof(T)` for leaves) with **zero runtime overhead**.↵
↵
**C. Write & Lazy Allocation (`operator[]`)**↵
↵
* The loop steps `shift` down to `8`, extracting `(x >> shift) & 15` and allocating `new void *[16]()` only on `nullptr`.↵
↵
* At `shift = 4` (`depth = LEVELS - 2`), it allocates the leaf array `new T[16]()` and indexes the lowest 4 bits via `[x & 15]`.↵
↵
**D. Read-Only Lookup (`query`)**↵
↵
* Unlike `operator[]`, `query(x)` returns `T{}` immediately upon hitting any `nullptr`, guaranteeing $O(0)$ memory allocation when querying absent keys.↵
↵
**E. Recursive Cleanup (`clear_node`)**↵
↵
* At `depth == LEVELS - 2`, child pointers `curr[i]` point directly to leaf arrays (`T[16]`), so they are deleted via `delete[] static_cast<T *>(curr[i])` without deeper recursion.↵
↵
---↵
↵
### 7. Dynamic Depth Scaling & Optimization Rules↵
↵
Scale `LEVELS` to match your problem's exact constraint ceiling (`ceil(bits / 4)`):↵
↵
* **Up to $4 \cdot 10^9$ (32-bit):** `LEVELS = 8`, `START_SHIFT = 28` — Standard array values ($A_i \le 10^9$).↵
↵
* **Up to $4.5 \cdot 10^{15}$ (52-bit):** `LEVELS = 13`, `START_SHIFT = 48` — Prefix sums up to $10^{14}$.↵
↵
* **Up to $1.15 \cdot 10^{18}$ (60-bit):** `LEVELS = 15`, `START_SHIFT = 56` — Grid/tree XOR paths up to $10^{18}$.↵
↵
* **Up to $1.8 \cdot 10^{19}$ (64-bit):** `LEVELS = 16`, `START_SHIFT = 60` — Full `uint64_t` keys or Zobrist hashes.↵
↵
**Three Contest Optimization Rules:**↵
↵
1. **Tighten `LEVELS`:** Never default to 16 levels unless keys truly use all 64 bits; shaving off unnecessary levels cuts millions of pointer hops.↵
↵
2. **Asymmetric Meet-in-the-Middle:** Insert fewer states with `operator[]` and perform more lookups with zero-allocation `query()`.↵
↵
3. **Use `_exit(0)` on Single-Testcase Tasks:** When allocating $10^5+$ nodes, `cout.flush(); _exit(0);` skips destructor teardown time and lets the OS reclaim memory in bulk.↵
↵
---↵
↵
### 8. Battle-Tested Practice Problems↵
↵
I validated the **Nibble Trie** across **15 problems**: 10 medium problems for practicing `LEVELS` tuning and bit-packing, and 5 heavy stress-test problems.↵
↵
**Part 1: Medium & Warm-Up Problems (10 Problems)**↵
↵
1. **[CF 702B — Powers of Two](https://codeforces.me/problemset/problem/702/B)** (`LEVELS = 8`) ↵
32-bit frequency counting ($a_i \le 10^9$) to find pairs summing to $2^k$.↵
↵
2. **[CF 1598C — Delete Two Elements](https://codeforces.me/problemset/problem/1598/C)** (`LEVELS = 8`) ↵
Two-sum frequency lookups over $a_i \le 10^9$ using zero-allocation `query()`.↵
↵
3. **[CF 1790D — Matryoshkas](https://codeforces.me/problemset/problem/1790/D)** (`LEVELS = 8`) ↵
Sparse frequency map over doll sizes up to $10^9$.↵
↵
4. **[CF 977F — Consecutive Subsequence](https://codeforces.me/problemset/problem/977/F)** (`LEVELS = 8`) ↵
Dynamic programming transitions indexed directly by array values $a_i \le 10^9$.↵
↵
5. **[CF 1915E — Romantic Glasses](https://codeforces.me/problemset/problem/1915/E)** (`LEVELS = 13`) ↵
Shifted alternating prefix sums up to $2 \cdot 10^{14}$ stored as 52-bit keys.↵
↵
6. **[CF 1426D — Non-zero Segments](https://codeforces.me/problemset/problem/1426/D)** (`LEVELS = 13`) ↵
Tracking visited prefix sums up to $2 \cdot 10^{14}$ using `Nibble_Trie<bool, 13>`.↵
↵
7. **[CF 1931D — Divisible Pairs](https://codeforces.me/problemset/problem/1931/D)** (`LEVELS = 15`) ↵
Packing remainder pairs `(a[i] % x, a[i] % y)` into a 60-bit key `(uint64_t(r1) << 30) | r2`.↵
↵
8. **[CF 1974C — Beautiful Triple Pairs](https://codeforces.me/problemset/problem/1974/C)** (`LEVELS = 15`) ↵
Packing 20-bit triples ($a_i \le 10^6$) into 60-bit keys to count near-matching triplets.↵
↵
9. **[CF 651C — Watchmen](https://codeforces.me/problemset/problem/651/C)** (`LEVELS = 16`) ↵
Packing 2D coordinates ($|x_i|, |y_i| \le 10^9$) into 62-bit keys `((uint64_t(x + 1e9)) << 31) | uint64_t(y + 1e9)`.↵
↵
10. **[CF 1133D — Zero Quantity Maximization](https://codeforces.me/problemset/problem/1133/D)** (`LEVELS = 16`) ↵
Packing reduced slope fractions $(p, q)$ into 62-bit keys to avoid floating-point precision loss.↵
↵
**Part 2: Heavy Stress-Test Problems (5 Problems)**↵
↵
11. **[CF 1771F — Hossam and Range Minimum Query](https://codeforces.me/problemset/problem/1771/F)** (`LEVELS = 8`) ↵
Forced-online queries immune to anti-hash hacks where coordinate compression is impossible.↵
↵
12. **[CF 877F — Ann and Books](https://codeforces.me/problemset/problem/877/F)** (`LEVELS = 13`) ↵
Mo's algorithm with runtime-generated prefix sums up to $10^{14}$; tests `query()` zero-allocation speed.↵
↵
13. **[CF 1006F — Xor-Paths](https://codeforces.me/problemset/problem/1006/F)** (`LEVELS = 15`) ↵
60-bit XOR Meet-in-the-Middle using an asymmetric split to keep memory under 256 MB.↵
↵
14. **[CF 1709E — XOR Tree](https://codeforces.me/problemset/problem/1709/E)** (`LEVELS = 8`) ↵
Small-to-large merging on trees; stresses rapid trie creation and cleanup (`clear()`).↵
↵
15. **[CF 1418G — Three Occurrences](https://codeforces.me/problemset/problem/1418/G)** (`LEVELS = 16`) ↵
Sliding-window frequency tracking over 64-bit Zobrist hashes ($N \le 5 \cdot 10^5$) with zero collision risk.



