← Writing

An autocomplete smaller than the list it completes

30 min readSystemsGoData StructuresPerformanceTries
Contents

A doctor types fem shaft frac into a diagnosis search box. Before the next keystroke lands, the box has to find, among 74,879 diagnoses, every description with a word starting fem, a word starting shaft and a word starting frac, rank them, and show the best ten. That part is easy. This post is about how small the thing doing it can be, and the answer turned out to be smaller than the list it searches: every description, every word and every code, searchable, in 4,080 KB. The text file it was all read from is 6,275 KB.

The same search written in plain Go takes 13,711 KB. The difference is a trie stored as a string of bits and navigated with nothing but rank and select, the two operations Succincter provides, which Finding Errors in Log Streams introduced. This post builds that trie, measures it against plain Go, and is honest about what the space costs: about 30 microseconds a keystroke. Then it looks at what the vocabulary itself says about fixing typos, which is that a medical search box should be very careful about doing it.

Every number here was measured on an Intel Core Ultra 9 285K under Go 1.27.4 on Windows, against the ICD-10-CM release for fiscal year 2027. The code is examples/autocomplete in the Succincter repository, and Run it yourself at the end reproduces all of it.

What you need to follow this: Go, or any language with arrays and binary search. Every data structure is introduced before it is used, including tries, rank and select, so you don’t need to have read the earlier Succincter post. A KB in this post is 1,024 bytes, which is what Go’s memory statistics count in.

1. What we are searching

ICD-10-CM is the code set American healthcare uses to record diagnoses: I10 is essential hypertension, E11.22 is type 2 diabetes with diabetic chronic kidney disease. The National Center for Health Statistics publishes it every year as free downloads. One of them is a plain text file with one code per line, padded to eight columns and followed by its description:

A000    Cholera due to Vibrio cholerae 01, biovar cholerae
A001    Cholera due to Vibrio cholerae 01, biovar eltor
A009    Cholera, unspecified

This post uses the 2027 release, icd10cm-codes-2027.txt, in effect since 1 October 2026. Before designing anything, it is worth knowing what is in it:

codes74,879
description text5,676,411 bytes, 75.8 per description
shortest descriptionsKuru, Colic, Ainhum
longest228 bytes
words779,845 in all, 10.4 per description
distinct words7,508
codes of seven characters51,587
descriptions containing “encounter”36,802
descriptions ending “, sequela”12,453

All of it is plain ASCII, and no two codes share a description. The longest one shows where the length comes from:

Injury of right internal carotid artery, intracranial portion, not elsewhere classified with loss of consciousness greater than 24 hours without return to pre-existing conscious level with patient surviving, subsequent encounter

The last three rows of the table are the code set’s habit of saying everything in full. Many injury codes take a seventh character that records the encounter: the first visit, a follow-up, or the sequela, the after-effects. Each of these is a separate code with its own complete description, so Unspecified fracture of shaft of right femur appears sixteen times, followed by , initial encounter for closed fracture, , subsequent encounter for open fracture type I or II with routine healing, and fourteen more. That repetition is where the compression in this post comes from, and it is also where its limits are.

2. What the box has to do

A clinician does not type descriptions from the beginning. They type fragments of the words they remember, in whatever order: femur shaft frac, type 2 diab kid, crohn. So the box:

  1. lower-cases the query and splits it into tokens on anything that is not a letter or digit;
  2. treats every token as the start of a word, so frac matches fracture;
  3. returns the descriptions that contain a match for every token, in any order;
  4. shows the best ten, with their codes.

“Best” needs a rule, and this post uses the simplest one that could work: shortest description first, alphabetical among equals. A shorter description is usually the more general diagnosis, and the general one is usually the right place to start. It has real failures, which section 9 shows. The reason to use it anyway is that, as we will see in section 5, a LOUDS trie produces exactly this order without being asked.

Here is the finished box on two queries:

"type 2 diab kid"
    E1122    Type 2 diabetes mellitus with diabetic chronic kidney disease
    E1129    Type 2 diabetes mellitus with other diabetic kidney complication
"crohn"
    K50914   Crohn's disease, unspecified, with abscess
    K50913   Crohn's disease, unspecified, with fistula
    K50114   Crohn's disease of large intestine with abscess
    K50113   Crohn's disease of large intestine with fistula
    K50014   Crohn's disease of small intestine with abscess

3. The plain Go version

Matching every token in any order is a job for an inverted index: for each distinct word, the sorted list of descriptions that contain it. That list is called a posting list. ICD-10-CM has 7,508 distinct words and 727,185 postings, one for each word in each description that contains it.

Give each description an id from 0 to 74,878 in ranking order: id 0 is Kuru, id 1 is Colic, and so on, shortest first. Then the search is set arithmetic on bit sets:

  • For each token, find every word that starts with it. In a sorted list of words those are consecutive, so two binary searches find them.
  • Set one bit per description for every posting of every one of those words. That is the set of descriptions matching this token. With 74,879 descriptions a bit set is 9.1 KB.
  • AND the sets of all the tokens together.
  • Read off the first ten set bits. Ids are in ranking order, so the ten lowest ids are the top ten, and nothing needs sorting.

The matching loop is shared by both versions in this post. Only orPrefix, which ORs one token’s words into a bit set, differs:

func match(query string, k int, acc, cur bitset, orPrefix func(tok string, into bitset) bool) []uint32 {
	toks := tokens(query)
	if len(toks) == 0 {
		return nil
	}
	for i, tok := range toks {
		into := acc
		if i > 0 {
			into = cur
		}
		into.clear()
		if !orPrefix(tok, into) {
			return nil
		}
		if i > 0 {
			acc.intersect(cur)
		}
	}
	return acc.first(k, nil)
}

first walks the bit set a 64-bit word at a time, using bits.TrailingZeros64 to jump to each set bit:

func (b bitset) first(k int, out []uint32) []uint32 {
	for i, w := range b {
		for w != 0 && len(out) < k {
			out = append(out, uint32(i*64+bits.TrailingZeros64(w)))
			w &= w - 1
		}
		if len(out) == k {
			break
		}
	}
	return out
}

The plain version stores what you would expect: every description and code as a Go string, the sorted word list, and each posting list as a []uint32. It is fast. Over the 254 keystrokes of twelve typed queries, the median keystroke takes 2.2 µs, and the slowest takes 63.5 µs.

It weighs 13,711 KB, more than twice the text file it was loaded from. The descriptions on their own account for 7,245 KB of that, because every Go string carries a 16-byte header (a pointer and a length), and its bytes are rounded up to one of the allocator’s size classes. The rest is codes, words, and four bytes for every one of the 727,185 postings.

Most of that is the descriptions, and they are the most repetitive part, so they are where to start.

4. A trie, and why the obvious one is enormous

ICD-10-CM’s descriptions repeat their beginnings a great deal: Unspecified fracture of shaft of right femur, … sixteen times, Type 2 diabetes mellitus with … 87 times. Put all 74,879 in a trie and it has 1,641,720 nodes, one per edge plus the root. That is 1,641,719 characters actually stored, out of 5,676,411 in the text. Seventy-one per cent of the characters are a prefix some other description already spelled.

The textbook trie spends that saving at once. Here is one written the obvious way in Go, with a node per heap object and a sorted label slice to binary-search for the next child:

type pnode struct {
	labels []byte
	kids   []*pnode
	final  bool
}

It takes 127,832 KB, 79.7 bytes per node and 17.6 times the strings it replaced. Two slice headers are 48 bytes before a node holds anything. Every child costs an 8-byte pointer and a label byte in two more allocations, and each allocation is rounded up to its size class. The characters saved by sharing prefixes are a few bytes each, and the pointers spent to share them cost far more.

The fix is to stop storing pointers at all.

5. LOUDS: a tree as a string of bits

The level-order unary degree sequence, or LOUDS, is due to Guy Jacobson (Space-efficient Static Trees and Graphs, FOCS 1989). It describes the shape of a tree in about two bits per node:

  1. Number the nodes breadth first: the root is 0, then its children in label order, then their children, level by level.
  2. For each node in that order, write one 0 per child, then a 1.

That bit string is called shape, and it is the whole tree: n nodes give n − 1 zeros (one for every node except the root, written by its parent) and n ones, so 2n − 1 bits. There is no way to do much better. The number of distinct ordered trees with n nodes grows like 4ⁿ, so telling them apart takes about log₂ 4ⁿ = 2n bits whatever the encoding.

Two arrays complete the trie:

  • labels[id] is the character on the edge into node id, one byte per node;
  • final has one bit per node, 1 where a stored string ends.

Jacobson’s original writes the 1s for the children and a 0 to end the block. This post writes them the other way round, 0s for children and a 1 to end each block, so that the operation the search uses on every keystroke is select over 1s, which is the one Succincter has.

Here are the five words from the box above, as a trie and as the three arrays:

Five words, one trie, three arrays

Type a prefix or click a node. Each step reads two Selects on shape and searches a few labels; nothing else is stored.

shape · bits, one block per node
labels · the letter on the edge into each node
final · 1 where a word ends
the walk the subtree under it a word ends here; #n is its key id

    Moving around with two selects

    Node k’s block is everything after the k-th 1 up to and including the (k+1)-th 1, because the blocks are written in node order and each ends with a 1. So:

    • the block starts at start = select(k) + 1 (at 0 for the root);
    • it ends at end = select(k + 1), the position of its own 1;
    • the 0s between them are its children, so the node has end − start children.

    Which ids do those children have? Every node except the root is written as a 0 by its parent. In breadth-first order, the j-th 0 in the string is node j. Before start there are exactly k 1s, which are the ends of blocks 0 to k − 1. That leaves start − k zeros, so the first child is node start − k + 1, and the rest follow consecutively.

    Follow it on the figure with the prefix ili. The root’s block starts at 0, and select(1) = 1, so it is a single 0: one child, node 1, labelled i. Node 1’s block starts after select(1) = 1 and ends at select(2) = 3, so it holds one child, node 2, labelled l. Node 2’s block starts after select(2) = 3 and ends at select(3) = 6. That gives bits 4 and 5, two children, nodes 3 and 4, labelled e and i, and a binary search over those two labels picks node 4. Nowhere did the walk read a pointer.

    In Go, on top of Succincter’s RankSelector interface:

    func (t *Louds) children(k int) (first, n int) {
    	start := 0
    	if k > 0 {
    		start = t.shape.Select(k) + 1
    	}
    	end := t.shape.Select(k + 1)
    	return start - k + 1, end - start
    }
    
    func (t *Louds) child(k int, c byte) int {
    	first, n := t.children(k)
    	ls := t.labels[first : first+n]
    	i := sort.Search(n, func(i int) bool { return ls[i] >= c })
    	if i < n && ls[i] == c {
    		return first + i
    	}
    	return -1
    }
    

    Building it needs no tree at all. The strings are sorted, so the strings below any node form a consecutive run. A queue of runs, processed in order, is the breadth-first traversal:

    func NewLouds(keys []string, shapeBits, finalBits Bits) (*Louds, []int32) {
    	// A node is the run of sorted keys sharing its first depth bytes.
    	type span struct{ lo, hi, depth int32 }
    	queue := []span{{0, int32(len(keys)), 0}}
    	var shape, final []bool
    	var labels []byte
    	var order []int32
    	labels = append(labels, 0) // the root has no incoming edge
    
    	for head := 0; head < len(queue); head++ {
    		s := queue[head]
    		lo := s.lo
    		// Sorted order puts the key that ends here first.
    		if lo < s.hi && int32(len(keys[lo])) == s.depth {
    			final = append(final, true)
    			order = append(order, lo)
    			lo++
    		} else {
    			final = append(final, false)
    		}
    		for lo < s.hi {
    			c := keys[lo][s.depth]
    			hi := lo + 1
    			for hi < s.hi && keys[hi][s.depth] == c {
    				hi++
    			}
    			queue = append(queue, span{lo, hi, s.depth + 1})
    			labels = append(labels, c)
    			shape = append(shape, false)
    			lo = hi
    		}
    		shape = append(shape, true)
    	}
    	t := &Louds{
    		shape:  shapeBits(shape),
    		final:  finalBits(final),
    		labels: append([]byte(nil), labels...), // without append's spare capacity
    		nodes:  len(queue),
    		keys:   len(order),
    	}
    	return t, order
    }
    

    shapeBits and finalBits choose the bit-vector encoding, plain Succincter or RRR, for each array separately. Both satisfy the same interface, so the trie code never knows which one it has.

    The ranking was free

    Each stored string gets a number, its key id: the rank of its node in final, that is, how many strings end at lower-numbered nodes. In the figure, ilia is #0, and ileum, ileus, iliac and ilium are #1 to #4.

    Look at the order that produces. Nodes are numbered level by level, and a string’s final node sits at the level equal to its length. So every shorter string gets a lower id than every longer one, and strings of equal length are in alphabetical order, because within a level the nodes are in order of their paths. Key ids are shortest first, then alphabetical, which is exactly the ranking from section 2. Build the trie of all 74,879 descriptions, and each description’s key id is its id in the ranking order the bit sets use. Nothing needs mapping, and NewLouds’s order result goes unused for the descriptions. The tests check this on every description.

    6. The descriptions live in the trie

    A trie that indexes the descriptions still needs the text kept somewhere to display it. This one does not, because the text is the paths. To show description id, find its node, which is the (id+1)-th 1 in final, and climb to the root, collecting the labels on the way.

    Climbing needs a node’s parent. Child c is the c-th 0 in shape, and its parent is the block that 0 sits in, which is the number of 1s before it. That takes a select over 0s, and Succincter has none. But it does not need one. If the parent is p, the 0 sits at position c − 1 + p, because c − 1 zeros and p ones come before it. p is the smallest value for which the first c + p bits contain exactly p ones, and a binary search over p with rank finds it:

    func (t *Louds) parent(c int) int {
    	lo, hi := 0, c-1
    	for lo < hi {
    		p := (lo + hi) / 2
    		if t.shape.Rank(c+p) > p {
    			lo = p + 1
    		} else {
    			hi = p
    		}
    	}
    	return lo
    }
    
    func (t *Louds) Key(id int, buf []byte) []byte {
    	buf = buf[:0]
    	for k := t.final.Select(id + 1); k > 0; k = t.parent(k) {
    		buf = append(buf, t.labels[k])
    	}
    	for i, j := 0, len(buf)-1; i < j; i, j = i+1, j-1 {
    		buf[i], buf[j] = buf[j], buf[i]
    	}
    	return buf
    }
    

    With 1.6 million nodes that is about 21 rank calls per character. It is the slowest thing in this post, and spelling every description back out measures it at 88.2 ns per character, or 6.7 µs for the average description. Only the ten results shown on a keystroke are ever spelled out, which keeps that cost bounded, as section 8 shows.

    What the 74,879 descriptions cost, stored this way, with three choices of bit vector:

    encoding of shape / finalKBbits per nodebits per character of text
    plain / plain2,90614.504.19
    plain / RRR2,61213.043.77
    RRR / RRR2,32211.583.35

    The text took 7,245 KB as Go strings and 5,543 KB as bare bytes. The trie holds the same text searchably in less than half a byte per character.

    Most of those bits are the letters. labels is 8 bits per node, whatever happens to the rest. shape is 2 bits per node, and Succincter’s rank index roughly doubles it to a little over 4. The final vector is the interesting one. Only 74,879 of its 1,641,720 bits are 1, which is 4.6 per cent, and that sparse, lopsided case is what RRR’s README says it is for. Switching final to RRR saves 294 KB, and costs almost nothing in speed, because the search touches final once per level and once per result, while it touches shape many times. Switching shape to RRR saves another 290 KB, but costs about 8 times as much per character spelled out (728 ns), because parent calls rank about 21 times per character and every RRR rank decodes a block. The index uses plain shape and RRR final.

    7. Words, and a subtree in a few ranges

    The second trie holds the 7,508 distinct words: 33,015 nodes in 59 KB. A token is a prefix, so the search finds its node in the word trie and then needs every word below it, all 684 of them for a one-letter token like s.

    The obvious way to list a subtree is to walk it node by node, calling children at each one, which costs two selects per node. But breadth-first numbering has a property worth using. Take the subtree under node k, and look at one level of it. Its nodes on that level are consecutive ids, because their parents were consecutive on the level above, and the children of consecutive nodes are written consecutively. It is true at the first level, where the subtree is just k, so by induction it is true at every level.

    So a whole subtree is one run of ids per level. The children of a run of nodes [a, b) take the same arithmetic as the children of one node, applied to a run of blocks. The blocks start after select(a) and end at select(b), and they contain b − 1 − a ones of their own. Every other bit in that span is a child. Key ids are ranks in final, so the keys in a run of nodes are a run of key ids too:

    func (t *Louds) Ranges(k int, fn func(lo, hi int)) {
    	a, b := k, k+1 // the subtree's nodes on this level are [a, b)
    	for a < b {
    		if lo, hi := t.final.Rank(a), t.final.Rank(b); lo < hi {
    			fn(lo, hi)
    		}
    		// Blocks a..b-1 run from just after the a-th 1 to the b-th 1, and
    		// hold b-1-a of their own terminating 1s; the rest are children.
    		start := 0
    		if a > 0 {
    			start = t.shape.Select(a) + 1
    		}
    		end := t.shape.Select(b)
    		first := start - a + 1
    		a, b = first, first+(end-start)-(b-1-a)
    	}
    }
    

    That is two selects and two ranks per level, however many nodes the level holds. The longest word starting with s has 19 letters, so all 684 of those words come out as at most 19 runs of word ids. The figure above does the same for ili: nodes 6 and 7, then 10 and 11, which hold key ids 0 and then 3 to 4.

    That shapes how the posting lists are stored. They are laid out in word-id order, so the lists for a run of word ids are one contiguous stretch of memory. Each list stores gaps, the differences between consecutive ids, rather than the ids themselves, written as variable-length integers. A varint spends one byte for every 7 bits a number needs, so a small gap fits in one byte. ICD-10-CM’s words are common enough that the gaps are small. The 727,185 postings take 833 KB, 1.17 bytes each, against 4 bytes each as uint32. Decoding is a few shifts per posting:

    func orList(list []byte, into bitset) {
    	id := uint32(0)
    	for i := 0; i < len(list); {
    		var gap uint32
    		for shift := 0; ; shift += 7 {
    			b := list[i]
    			i++
    			gap |= uint32(b&0x7f) << shift
    			if b < 0x80 {
    				break
    			}
    		}
    		id += gap
    		into[id/64] |= 1 << (id % 64)
    	}
    }
    

    The bill for the whole index, with plain shape and RRR final:

    partKB
    description trie: every description, searchable and displayable2,612
    codes, 7 bytes each, space-padded512
    posting lists as varint gaps, plus 4-byte offsets833 + 29
    word trie59
    two bit sets for the search18
    measured, including the structs that hold them4,080

    What the index weighs

    Heap bytes each structure keeps alive, measured. The dashed line is the text file everything was built from.

    Go strings, slices and pointers LOUDS on succincter

    Everything needed to answer a keystroke and draw its results fits in 4,080 KB. That is 0.65 times the 6,275 KB text file, and 0.30 times plain Go. With RRR on both vectors it drops to 3,781 KB, at a price the next section shows.

    8. What a keystroke costs

    Before timing anything, the program checks that all four versions — plain Go, and LOUDS with each of the three encodings — return identical top-ten lists on all 254 keystrokes. The tests go further: tries over random strings built 300 times in both encodings and checked against brute force on every prefix, Ranges checked against the node-by-node walk, all 74,879 descriptions spelled back out and compared, and 3,000 random queries of one to three tokens compared between plain Go and LOUDS.

    Then it times every keystroke of the twelve queries:

    medianp90slowest keystroke
    plain Go2.2 µs23.5 µs63.5 µs
    LOUDS, plain / plain31.2 µs82.3 µs188.7 µs
    LOUDS, plain / RRR31.4 µs79.4 µs214.4 µs
    LOUDS, RRR / RRR227.8 µs449.9 µs739.3 µs

    At the median, the LOUDS index is about fourteen times slower than plain Go. One query, keystroke by keystroke, shows where the time goes:

    What each keystroke costs

    Microseconds to answer each prefix of fracture shaft right femur, top ten with their text. Lower is faster.

    plain Go LOUDS (plain shape, RRR final) plain Go + 88.2 ns × characters shown

    Most of the gap is the spelling. After fracture shaft right femur, the ten results add up to 589 characters. At 88.2 ns per character that is 52.0 µs, and the measured gap between LOUDS and plain Go on that keystroke is 55.7 µs. The dashed line adds the spelling cost to plain Go’s time at every keystroke, and the LOUDS line follows it.

    Where it doesn’t is the four one-letter tokens: the f of fracture, then s, r, and the f of femur. A one-letter token matches hundreds of words. s matches 684 words with 71,243 postings between them, which all have to go into the bit set. Plain Go reads them as uint32s from separate slices. The LOUDS index decodes varints, and its time rises well above the dashed line. The worst keystroke in the whole run took 214.4 µs.

    Is that too slow? A 60 Hz screen redraws every 16.7 ms, so the worst keystroke uses 1.3 per cent of one frame. Nobody will see the difference between 2 and 31 microseconds, but they would notice 13,711 KB against 4,080 KB in a page download, on a phone, or in a process that runs many of these indexes. RRR on shape is the exception. It saves 300 KB more and makes every result 8 times slower to spell, so its median is 227.8 µs, and that trade is worse than the others.

    If memory is not the constraint — a server with this one index — use the plain version: it is simpler and faster. The trie is for when the bytes matter more than the microseconds.

    9. What it does not do

    The box searches the words the code set uses, and only those. Some queries show what that leaves out:

    "heart attack"
    "mi"
        H5703    Miosis
        Q172     Microtia
        M2606    Microgenia
        Q185     Microstomia
        Q02      Microcephaly
    "myocard inf"
        I400     Infective myocarditis
        I252     Old myocardial infarction
        I21A1    Myocardial infarction type 2
        I21A9    Other myocardial infarction type
        I219     Acute myocardial infarction, unspecified
    
    • heart attack finds nothing. No description contains those words. The code set says myocardial infarction.
    • mi is not myocardial infarction. It is a prefix, and it matches miosis and micro-. Clinicians’ abbreviations are not in the descriptions. Synonyms and abbreviations need a separate list mapping them to codes. The code set does ship a separate alphabetic index, but this post does not use it.
    • Shortest-first is not best-first. myocard inf puts Infective myocarditis first, because both of its words match a prefix and it is the shortest description that does. fem shaft frac puts Other fracture of shaft of left femur, sequela first, because , sequela is shorter than , initial encounter for closed fracture, and that is almost never the code a clinician starting a record wants. Real ranking needs to know how often each code is used, and the code set does not carry that. A usage count per code would be one more array beside the codes. Using it would mean sorting the matches, because the ten lowest ids would no longer be the ten best.
    • The trie shares beginnings, not endings. The encounter phrases repeat at the end of 36,802 descriptions, and a trie stores every copy. Sharing endings instead doesn’t help on its own: the trie of the same descriptions spelled backwards has 1,744,520 nodes, more than the 1,641,720 of the forward one. A structure that shares both ends — a minimal acyclic automaton, which is what Lucene’s FSTs are — is the natural next step. I have not built one, so I have no number for it.

    10. Why it doesn’t fix your typos

    Most autocompletes forgive typing errors: type fracure and they offer fracture anyway. The usual method is edit distance, the number of single-letter insertions, deletions or substitutions between two words, and an autocomplete that allows one edit offers every word one edit away. The same trie could support it: a Levenshtein automaton (Schulz and Mihov, 2002) can be walked through the trie alongside the query.

    But the ICD-10-CM vocabulary is not forgiving. Among its 7,120 distinct alphabetic words of four or more letters, 1,737 — 24.4 per cent — have another word one edit away, making 1,297 pairs. A lot of them are harmless plurals (cyst/cysts, mycosis/mycoses). These are not:

    one edit apartwhat each means
    ileum / iliumthe last part of the small intestine / the large bone of the pelvis
    ileum / ileusthe same part of the intestine / a stop in the gut’s movement
    arteritis / arthritisinflamed arteries / inflamed joints
    dysphagia / dysphasiadifficulty swallowing / difficulty with language
    dysphasia / dysplasiadifficulty with language / abnormal growth of cells
    perineal / peronealof the perineum / of the outer lower leg
    ureteral / urethralthe tubes from kidney to bladder / the tube out of the bladder
    abductor / adductormuscles that move a limb away from the body / towards it
    myelitis / pyelitisinflammation of the spinal cord / of the kidney’s pelvis

    Here are ileum and ilium in the box:

    "ileum"
        C172     Malignant neoplasm of ileum
        D3A012   Benign carcinoid tumor of the ileum
        C7A012   Malignant carcinoid tumor of the ileum
        Q412     Congenital absence, atresia and stenosis of ileum
    "ilium"
        S32392S  Other fracture of left ilium, sequela
        S32391S  Other fracture of right ilium, sequela
        S32302S  Unspecified fracture of left ilium, sequela
        S32399S  Other fracture of unspecified ilium, sequela
        S32301S  Unspecified fracture of right ilium, sequela
    

    A box that forgives one edit shows a bowel tumour to someone looking for a pelvic fracture, and the reverse. Each of these is the right answer for some query, so ranking alone cannot rule them out. A forgiving box would have to show the guess as a guess, so that nobody picks it without seeing that it is not what they typed. My rules would be: exact prefix matches always rank above fuzzy ones, a fuzzy match is marked as a correction, and the top result is never selected automatically when it is one. This box doesn’t forgive at all, which is the safe end of that choice: a typo gives no results, and the person types it again.

    11. What to take away

    • A trie of real text shares most of its characters. ICD-10-CM’s descriptions, in a trie, keep 28.9 per cent of their characters. A trie built from pointers spends that saving many times over: 79.7 bytes per node.
    • LOUDS keeps the sharing and drops the pointers. It stores a tree in 2n − 1 bits plus one label byte per node, and moves around it with two selects per step. On top of Succincter that is 13 bits per node, or 3.77 bits per character of the original text.
    • Breadth-first numbering does two jobs for free. Key ids come out shortest first, then alphabetical, which was the ranking. And a subtree is one run of consecutive ids per level, so listing it takes two selects per level rather than per node.
    • Choose the encoding per vector. RRR suits the sparse final vector, which saves memory at no visible cost. On shape, which every step reads, it costs 8 times as much per character spelled.
    • The space costs time, and the cost is measurable. About 88 ns per character shown, and 31 µs per keystroke at the median, which is fine for a search box and wrong for a hot loop.
    • Ask whether your domain wants typos fixed. In this one, a quarter of the words are one edit away from another word, and some of those pairs are different parts of the body.

    Run it yourself

    The example is in Succincter’s repository. Download the 2027 code descriptions from the NCHS FTP site, unpack them, and point the program at the codes file:

    git clone https://github.com/shaia/succincter
    cd succincter
    curl -O "https://ftp.cdc.gov/pub/Health_Statistics/NCHS/Publications/ICD10CM/2027/icd10cm-code-descriptions-2027.zip"
    unzip icd10cm-code-descriptions-2027.zip
    go run ./examples/autocomplete -data icd10cm-code-descriptions-2027/icd10cm-codes-2027.txt
    

    It prints the vocabulary table, the memory of every structure, the example queries, both timing tables and the typo count. Set PAIRS=1 to list all 1,297 one-edit pairs. The tests run against the real file when ICD10CM names it:

    ICD10CM=icd10cm-code-descriptions-2027/icd10cm-codes-2027.txt go test ./examples/autocomplete
    

    Your timings will differ from mine. The memory figures, the counts and the result lists should not.

    A note on the evidence

    What I observed. Every number comes from one program, examples/autocomplete, run on 20 November 2026. The machine was an Intel Core Ultra 9 285K under Windows 11, with Go 1.27.4 for windows/amd64. The data is icd10cm-codes-2027.txt from the NCHS archive icd10cm-code-descriptions-2027.zip, whose SHA-256 was:

    93e3ad6004badf470c55bfe679b748ae88fd9b2b421851e409eec382c7713b9a
    

    All the counts in sections 1 and 10 are the program’s output. The words and postings behind the token s in section 8 (684 and 71,243) come from a separate Python count with the same tokenisation, as do the sixteen femur codes and 87 diabetes descriptions in section 4, counted with grep.

    How memory was measured. Each structure is built from nothing but the loaded entries, inside a function that reads runtime.MemStats.HeapAlloc after a full garbage collection before and after the build. The figure is what the structure keeps alive, including its slices’ spare capacity. Plain Go copies every string it keeps, so it is charged for them. It is heap, not resident memory, and a KB is 1,024 bytes.

    How time was measured. The clock on this machine ticks in steps of about half a millisecond, which is far coarser than one search, so no single call is timed. Each keystroke is repeated until at least 20 ms have passed, and the figure is the mean. The four versions are interleaved keystroke by keystroke within one run, so they share whatever the machine was doing. Other programs were running on it. An earlier run of the same search code put the medians at 3.0 µs for plain Go and 38.5 µs for LOUDS, so treat the absolute times as good to about a third. The ratios held: 13 to 14 times at the median in both runs.

    What is checked, not assumed. The figure of the five-word trie computes its arrays with its own script. They match what the Go code builds for the same five words bit for bit, including the walk to ili and the two key runs below it. The claim that the description trie’s key ids are the ranking order is tested on all 74,879 descriptions.

    What is not measured. No fuzzy matching was built, so section 10 is an argument from the vocabulary, not from a typo-tolerant search. Its edit distance counts insertions, deletions and substitutions, not swapped neighbours. The meanings in its table are standard anatomy and pathology, and the table is not a clinical safety analysis. The ranking was never tested on clinicians, and section 9 shows why it would fail. The minimal automaton is a suggestion with no number behind it.

    What I would change. parent takes about 21 ranks per character. A select index over the 0s would turn that into one select, and would cut the 88 ns per character, at the cost of another vector the size of shape. Measuring that trade is the next experiment. The codes take 7 bytes each, but they use only 36 symbols, so a packed encoding could save much of their 512 KB.

    More