Algorithm Search⌘K

Techniquecore

Front coding

Also called incremental encoding of sorted strings.

Stores each term of a sorted dictionary as the length of the prefix it shares with the previous term plus its remaining suffix.

Front coding is the technique of storing a sorted list of strings by writing, for each string, the length of the prefix it shares with the string before it, followed by the rest of the string. Sorted terms share long prefixes ("automata", "automate", "automatic"), so the shared part is written once and the dictionary of an inverted index gets much smaller. To keep lookups fast, the list is cut into blocks of kk strings, and the first string of each block is written in full, so a search can start at any block. The lengths are small numbers and are written with a variable byte code.

In plain words

In a dictionary, neighbors look alike: "automata" is followed by "automate", "automatic" and "automation". Writing all four words in full repeats "automat" four times. Front coding writes the first word in full, and for each next word it writes only how many letters it shares with the word before and the letters that are new. So "automate" becomes "7, then e".

To read a word back, the reader must know the word before it, and that one needs the one before it, and so on. To avoid reading the whole list for one word, the list is cut into small groups, and the first word of each group is written in full. A search jumps to the right group, then reads at most a few words in it.

When it applies

  • The strings are sorted. The order of lexicographic order puts strings with long common prefixes next to each other. On an unsorted list front coding still works, but it saves little.
  • The list is read more than it is changed. An insertion in the middle changes the prefix length of the next string and, with blocks, can move the block heads. Static dictionaries, index files and sorted runs suit it; a dictionary that changes often needs a tree.
  • Lookups can afford a short scan. A lookup decodes up to k−1k - 1 strings of a block after a binary search over the block heads.
  • The strings share prefixes. Long words of a large vocabulary, URLs, file paths and sorted keys gain much; short words of a small vocabulary gain little or nothing, as the toy example below shows.

The template

The encoder below writes the number of strings first, then each string as described. The holes to fill are in capitals.

  1. FRONT-ENCODE(t_0, ..., t_{n-1}, k) ▷ t sorted, k ≥ 1
  2. 1out ← WRITE-NUMBER(n)
  3. 2for i ← 0 to n - 1 do
  4. 3if i mod k = 0 then p ← 0 ▷ a block head is written in full
  5. 4else p ← LCP(t_{i-1}, t_i)
  6. 5append WRITE-NUMBER(p) to out
  7. 6append WRITE-NUMBER(|t_i| - p) and the bytes t_i[p..] to out
  8. 7return out

The holes. LCP is the length of the longest common prefix of two strings, in bytes. WRITE-NUMBER is the code of the lengths: the code here is a variable byte code with 7 bits per byte and the high bit on the last byte, so every length below 128 costs one byte. The block size kk trades space for lookup time: k=1k = 1 is no front coding, and k=nk = n is one block. The decoder reads in the same order and rebuilds tit_i as the first pp bytes of ti−1t_{i-1} followed by the bytes it reads; at a block head it needs nothing from before.

The invariant. After the decoder has read string ii, it holds tit_i exactly. At a block head this is because the string is written in full. Elsewhere it holds ti−1t_{i-1} by induction, and ti−1t_{i-1} and tit_i agree on their first pp bytes by the definition of LCP, so the first pp bytes of ti−1t_{i-1} followed by the rest give tit_i. This holds for any list, sorted or not, and for empty strings.

The cost. Encoding and decoding take time linear in the total length of the strings. The output has the stored rest bytes plus one or two length numbers per string. A lookup of a string xx makes a binary search over the ⌈n/k⌉\lceil n/k \rceil block heads, which needs an array of the byte offsets of the blocks, then decodes at most k−1k - 1 strings of one block.

A worked example. The four strings "automata", "automate", "automatic" and "automation" form one block with k=4k = 4.

string p rest bytes
automata (head) automata 1 + 8 = 9
automate 7 e 1 + 1 + 1 = 3
automatic 7 ic 1 + 1 + 2 = 4
automation 8 on 1 + 1 + 2 = 4

The block takes 20 bytes, against 39 bytes for the four strings each with a one-byte length. On the 50 terms of the toy collection the plain list with one-byte lengths takes 284 bytes, and front coding takes 292 bytes for k=4k = 4 and 279 for k=16k = 16. The words are short and share only 53 letters with their neighbors in all, often one or two, and the extra prefix byte of each string costs about as much as it saves.

Classic examples

  • The dictionary of an inverted index. Manning, Raghavan and Schuetze store the RCV1 dictionary as one long string with pointers, in 7.6 MB. Blocks of k=4k = 4, which need a term pointer only for every fourth term, bring it to 7.1 MB, and front coding inside the blocks to 5.9 MB.
  • Leaves of a B+ tree or a string B-tree. Keys in a leaf are sorted and share prefixes, so storing them front coded fits more keys in a disk page and makes the tree shallower.
  • The LCP array. The sorted suffixes of a text, written with the length of the prefix that each shares with the one before, are a front coding of the suffixes; the LCP array is exactly the list of those prefix lengths.
  • A trie flattened in order. Walking a trie in order and writing, at each word, how far to go back up and which letters to add gives the same numbers as front coding. A radix tree stores each shared prefix once, as front coding does within a block.

Variations

  • Shared prefix of the block. Manning, Raghavan and Schuetze write the prefix common to the whole block once, after the first term, and then each other term as its length and the letters after that prefix. This is simpler to decode but saves less when the terms of a block share different prefixes.
  • Count from the end. Store how many bytes to remove from the end of the previous string, ∣ti−1∣−p|t_{i-1}| - p, in place of pp. The two numbers carry the same information, and the count from the end is small when long strings differ only near their ends.
  • Front coding with a code of the lengths. Use a bit-level code such as a gamma code for the prefix lengths, or pack both lengths in one byte when both are below 16.
  • Compressed strings. Code the rest bytes with a dictionary-based compressor or a Huffman code of the characters, on top of front coding.

Pitfalls

  • No block heads. With k=nk = n, every lookup decodes from the first string, in time linear in the list. Choose kk so that a block fits in a few cache lines or one disk read.
  • Prefix lengths in characters against bytes. For UTF-8 strings, a prefix length counted in characters cuts the bytes wrongly when the two strings differ inside a character. Compute LCP and slice on the same unit; the code here works on bytes throughout.
  • Trailing or missing data. The decoder must check that it reads exactly the encoded bytes. The code here raises an error when bytes are left over, so a padded or joined buffer does not decode silently to a wrong list.
  • Expecting a gain on short words. On a small vocabulary of short words, front coding can make the dictionary larger, as on the toy collection. Measure before choosing kk.
  • Updates in place. Inserting one string in the middle changes the prefix length of the string after it. Rebuild the block, not only the entry.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

front_coding.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/front-coding/. The authors are listed in prov/NH530P.jsonl.
"""Blocked front coding of a list of strings.

The list is cut into blocks of k strings. The first string of a block is
written in full, as its length and its bytes. Each other string is written
as the length of the prefix it shares with the string before it, the length
of the rest, and the bytes of the rest. Lengths are variable byte numbers,
and the output starts with the number of strings.
"""


def lcp(a: bytes, b: bytes) -> int:
    """Return the length of the longest common prefix of a and b. Cost O(min(|a|, |b|))."""
    n = min(len(a), len(b))
    i = 0
    while i < n and a[i] == b[i]:
        i += 1
    return i


def write_number(x: int, out: bytearray) -> None:
    """Append x >= 0 as a variable byte number: 7 bits per byte, the high bit set on the last byte."""
    while x >= 128:
        out.append(x & 127)
        x >>= 7
    out.append(x | 128)


def read_number(data: bytes, pos: int) -> tuple[int, int]:
    """Read a variable byte number at pos. Return it and the position after it."""
    x, shift = 0, 0
    while True:
        b = data[pos]
        pos += 1
        x |= (b & 127) << shift
        if b & 128:
            return x, pos
        shift += 7


def encode(terms: list[str], k: int = 4) -> bytes:
    """Front code the strings with blocks of k. Any list works; a sorted list compresses well.

    Precondition: k >= 1. Cost O(total length of the strings).
    """
    if k < 1:
        raise ValueError("k must be at least 1")
    out = bytearray()  # @line L1
    write_number(len(terms), out)
    prev = b""
    for i, t in enumerate(terms):  # @line L2
        s = t.encode()
        if i % k == 0:  # @line L3
            p = 0
        else:
            p = lcp(prev, s)  # @line L4
            write_number(p, out)  # @line L5
        write_number(len(s) - p, out)  # @line L6
        out += s[p:]
        prev = s
    return bytes(out)  # @line L7


def decode(data: bytes, k: int = 4) -> list[str]:
    """Return the list of strings that encode(terms, k) wrote into data. Cost O(|data| + total length)."""
    terms: list[bytes] = []
    n, pos = read_number(data, 0)
    prev = b""
    for i in range(n):
        p = 0
        if i % k != 0:
            p, pos = read_number(data, pos)
        r, pos = read_number(data, pos)
        s = prev[:p] + data[pos : pos + r]
        pos += r
        terms.append(s)
        prev = s
    if pos != len(data):
        raise ValueError("bad data")
    return [s.decode() for s in terms]
irtoy.py 76 lines
# SPDX-License-Identifier: MIT
# Shared helper of the information retrieval pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy collection of the information retrieval pages.

Eight short documents, four queries with graded judgments and one fixed
run. Tokens are the lower-case words split on spaces, with no stemming
and no stop words. The helper holds only the data and the statistics
tokenize, tf, df, cf, doc_len and avgdl. Scoring and metrics live on the
pages that define them.
"""

DOCS = {
    1: "binary search finds a key in a sorted array",
    2: "merge sort merges two sorted runs into one sorted array",
    3: "an inverted index maps each term to a posting list",
    4: "a posting list is a sorted list of document ids",
    5: "skip pointers speed up the merge of two posting lists",
    6: "a hash table finds a key in constant expected time",
    7: "search engines rank documents by a score for the query",
    8: "the sorted array of ids is compressed with gap encoding",
}

N = len(DOCS)

QUERIES = {
    "q1": "sorted array search",
    "q2": "posting list merge",
    "q3": "rank documents",
    "q4": "quantum circuit",
}

# Graded judgments: 2 is highly relevant, 1 is relevant, absent is 0.
QRELS = {
    "q1": {1: 2, 2: 1, 8: 1},
    "q2": {5: 2, 4: 1, 3: 1},
    "q3": {7: 2},
    "q4": {},
}

# A fixed run for the metric pages, as scores per query.
RUN = {
    "q1": {1: 2.0, 6: 2.0, 8: 1.5, 2: 1.0, 4: 1.0},
}


def tokenize(text):
    """Lower-case words split on spaces."""
    return text.lower().split()


_TOKENS = {d: tokenize(t) for d, t in DOCS.items()}


def tf(term, doc_id):
    """Number of times term occurs in document doc_id."""
    return _TOKENS[doc_id].count(term)


def df(term):
    """Number of documents that contain term."""
    return sum(1 for toks in _TOKENS.values() if term in toks)


def cf(term):
    """Number of occurrences of term in the whole collection."""
    return sum(toks.count(term) for toks in _TOKENS.values())


def doc_len(doc_id):
    """Number of tokens in document doc_id."""
    return len(_TOKENS[doc_id])


def avgdl():
    """Average document length in tokens."""
    return sum(len(toks) for toks in _TOKENS.values()) / N
test_front_coding.py 72 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/front-coding/. The authors are listed in prov/NH530P.jsonl.

import os.path
import random

import pytest

import irtoy
from front_coding import decode, encode, lcp, read_number, write_number


def test_example_of_the_page():
    terms = ["automata", "automate", "automatic", "automation"]
    data = encode(terms, 4)
    # count 4; 8 "automata"; 7 1 "e"; 7 2 "ic"; 8 2 "on"
    want = bytes([4 | 128, 8 | 128]) + b"automata" + bytes([7 | 128, 1 | 128]) + b"e"
    want += bytes([7 | 128, 2 | 128]) + b"ic" + bytes([8 | 128, 2 | 128]) + b"on"
    assert data == want
    assert len(data) - 1 == 20
    assert sum(1 + len(t) for t in terms) == 39
    assert decode(data, 4) == terms


def test_toy_vocabulary():
    vocab = sorted({t for d in irtoy.DOCS for t in irtoy.tokenize(irtoy.DOCS[d])})
    assert sum(1 + len(t) for t in vocab) == 284
    assert len(encode(vocab, 4)) - 1 == 292
    for k in range(1, 60):
        assert decode(encode(vocab, k), k) == vocab


def test_edge_cases():
    for k in (1, 2, 4):
        assert decode(encode([], k), k) == []
        assert decode(encode([""], k), k) == [""]
        assert decode(encode(["", "", "a", "a", "a"], k), k) == ["", "", "a", "a", "a"]
    long = ["x" * 300, "x" * 300 + "y", "x" * 1000]
    assert decode(encode(long, 3), 3) == long
    uni = ["café", "cafè", "naïve", "日本", "日本語"]
    assert decode(encode(uni, 2), 2) == uni
    with pytest.raises(ValueError):
        encode(["a"], 0)
    with pytest.raises(ValueError):
        decode(encode(["ab", "ac"], 4) + b"z", 4)


def test_numbers_and_lcp():
    for x in [0, 1, 127, 128, 255, 16383, 16384, 2**63 - 1]:
        out = bytearray()
        write_number(x, out)
        assert read_number(bytes(out), 0) == (x, len(out))
    rng = random.Random(5)
    for _ in range(500):
        a = bytes(rng.choice(b"ab") for _ in range(rng.randint(0, 6)))
        b = bytes(rng.choice(b"ab") for _ in range(rng.randint(0, 6)))
        assert lcp(a, b) == len(os.path.commonprefix([a, b]))


def test_random_round_trips():
    rng = random.Random(2009)
    for _ in range(1000):
        n = rng.randint(0, 30)
        letters = rng.choice(["ab", "abc", "abcdefghij", "aé日"])
        terms = ["".join(rng.choice(letters) for _ in range(rng.randint(0, 8))) for _ in range(n)]
        if rng.random() < 0.7:
            terms.sort()
        k = rng.randint(1, 8)
        data = encode(terms, k)
        assert decode(data, k) == terms
        # Each string costs at most its bytes and two one-byte lengths here.
        assert len(data) <= 5 + sum(2 + len(t.encode()) for t in terms)

References

  1. Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 5, Section 5.2.2 (the dictionary as a string, blocked storage with k = 4, front coding with Figure 5.7 and the automata example, the sizes 7.6 MB, 7.1 MB and 5.9 MB for Reuters-RCV1 in Table 5.2, and the cost of a lookup in a blocked dictionary)
  2. Ian H. Witten, Alistair Moffat and Timothy C. Bell, Managing Gigabytes, Compressing and Indexing Documents and Images, second edition, Morgan Kaufmann, 1999, Chapter 4, Section 4.1 (the storage of the lexicon, with front coding of the sorted terms and the use of blocks with a full term at the start of each)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • five exercises