Lesson contents

Tries and prefix search

A trie follows one character at a time. Words with the same beginning share a path. A separate end marker records a complete word.

Simple example

Store AB and AC. Follow A and count the two word endings below it. The prefix A is shared but is not itself a stored word.

StartA AB AC
Result2
lesson.zig
const std = @import("std");

fn show(value: i64) !void {
    var buffer: [64]u8 = undefined;
    var writer = std.fs.File.stdout().writer(&buffer);
    try writer.interface.print("{d}\n", .{value});
    try writer.interface.flush();
}

pub fn main() !void {
    const edgeA = [_]i64{1, -1, -1, -1};
    const edgeB = [_]i64{-1, 2, -1, -1};
    const edgeC = [_]i64{-1, 3, -1, -1};
    const ending = [_]i64{0, 0, 1, 1};
    const prefix: i64 = edgeA[0];
    try show((ending[@intCast(edgeB[@intCast(prefix)])] + ending[@intCast(edgeC[@intCast(prefix)])]));
}
Output
2
Advertisements

Everyday examples

Suggest book titles

The index stores CAR and CAT. Someone types CA. Which two titles remain possible?

StartCAR CAT
ResultCAR CAT

Follow C then A once. The R and T branches give the two completions.

Find matching route codes

The route codes are AB, ABC and AD. Which codes begin with AB?

StartAB ABC AD
ResultAB ABC

At the B node, include its own end marker before visiting the C child.

Check a short name

The directory stores ANNA. Someone enters ANN. Is that an exact match?

StartANNA
Result∅

The prefix path exists, but there is no word ending at the second N. Keep looking only for suggestions.

Cost and limits

Following a prefix takes one step per character when child lookup is constant time. Listing matches also takes work for the results. Mark word endings separately from branches.