Mot_sem's blog

By Mot_sem, history, 6 days ago, In English

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.


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

Nibble Trie In-Memory Architecture

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().

Detailed Hardware Latency & Byte-Level Memory Calculations

5. My C++ Implementation

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 (LEVELS = 8)
    32-bit frequency counting ($$$a_i \le 10^9$$$) to find pairs summing to $$$2^k$$$.

  2. CF 1598C — Delete Two Elements (LEVELS = 8)
    Two-sum frequency lookups over $$$a_i \le 10^9$$$ using zero-allocation query().

  3. CF 1790D — Matryoshkas (LEVELS = 8)
    Sparse frequency map over doll sizes up to $$$10^9$$$.

  4. CF 977F — Consecutive Subsequence (LEVELS = 8)
    Dynamic programming transitions indexed directly by array values $$$a_i \le 10^9$$$.

  5. CF 1915E — Romantic Glasses (LEVELS = 13)
    Shifted alternating prefix sums up to $$$2 \cdot 10^{14}$$$ stored as 52-bit keys.

  6. CF 1426D — Non-zero Segments (LEVELS = 13)
    Tracking visited prefix sums up to $$$2 \cdot 10^{14}$$$ using Nibble_Trie<bool, 13>.

  7. CF 1931D — Divisible Pairs (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 (LEVELS = 15)
    Packing 20-bit triples ($$$a_i \le 10^6$$$) into 60-bit keys to count near-matching triplets.

  9. CF 651C — Watchmen (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 (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)

  1. CF 1771F — Hossam and Range Minimum Query (LEVELS = 8)
    Forced-online queries immune to anti-hash hacks where coordinate compression is impossible.

  2. CF 877F — Ann and Books (LEVELS = 13)
    Mo's algorithm with runtime-generated prefix sums up to $$$10^{14}$$$; tests query() zero-allocation speed.

  3. CF 1006F — Xor-Paths (LEVELS = 15)
    60-bit XOR Meet-in-the-Middle using an asymmetric split to keep memory under 256 MB.

  4. CF 1709E — XOR Tree (LEVELS = 8)
    Small-to-large merging on trees; stresses rapid trie creation and cleanup (clear()).

  5. CF 1418G — Three Occurrences (LEVELS = 16)
    Sliding-window frequency tracking over 64-bit Zobrist hashes ($$$N \le 5 \cdot 10^5$$$) with zero collision risk.

Full text and comments »

  • Vote: I like it
  • +9
  • Vote: I do not like it