Proofs: FM-index
These are the human proofs of FM-index, at full length.
Backward search and LF walks on the FM-index are correct full
This proof shows: correctness, termination, time.worst.
Notation. has symbols coded , and with , unique and smallest. Positions and rows are 0-based, , and is the suffix array of , so the suffixes . when and otherwise. is the number of symbols of smaller than , and . Since is unique and smallest, no suffix of is a prefix of another, and suffixes compare at the first position where they differ.
Lemma 1 (block of a symbol). The rows whose suffixes start with are exactly , where is the number of in .
Proof. The suffixes are sorted, so those that start with smaller symbols come first, and there are of them, one for each position that holds a smaller symbol.
Lemma 2 (LF). Let with . Then .
Proof. Let be the rows with , and , so . Since , the suffixes are in the same order. These are all the suffixes that start with : a suffix with has , since , so exists, and at its row is . By Lemma 1 they fill the rows onward in this order. Row has , so the suffix is at row .
Lemma 3 (backward step). Let be a string and the rows whose suffixes start with . For a symbol of , the rows whose suffixes start with are .
Proof. A suffix starts with if and only if and starts with , that is, the row of is in and . By Lemma 2, the row of is . As runs over the rows in with , takes the consecutive values .
Theorem 1 (count). Lines L1 to L5 return the range of rows whose suffixes start with , or the empty range if does not occur; is the number of occurrences.
Proof. Before the loop, the range is all rows, which start with the empty string. Each round applies Lemma 3 with and . If is not in , no suffix starts with . Once a range is empty, all later ranges are empty, so stopping early is correct. After the loop the range is that of . The occurrences of a nonempty in are the suffixes of that start with , one row each, since does not contain .
Theorem 2 (locate). For each row of the range, lines L7 to L9 report , after at most LF steps.
Proof. Invariant: . It holds with . If is not sampled, then , so and Lemma 2 gives , and grows by 1. The position drops by one per step and every multiple of , including 0, is sampled, so the loop stops after at most steps and reports .
Theorem 3 (extract). The extraction returns .
Proof. It starts at the row of a sampled position , with . While , , so , and Lemma 2 moves to the row of . So it reads , and keeps those at positions below .
Time. The loop of L2 runs times with two rank queries each. Each reported occurrence takes at most LF steps, each one rank query. With checkpoints every rows, a rank query scans fewer than symbols; with a wavelet tree it takes time. So count is or , locate adds or , and extract takes steps. All loops are bounded, so the operations terminate.