Proofs: Lyndon array
These are the human proofs of Lyndon array, at full length.
LYNDON-ARRAY computes the longest Lyndon word at each index full
This proof shows: correctness, termination.
Notation. is a word over a totally ordered alphabet, with 0-based indices. Words are compared in lexicographic order, where a proper prefix is smaller, and is the suffix that starts at . The array is the inverse suffix array: if and only if , and all ranks are distinct. For , is the least with , or if there is none. We use two results from the Lyndon factorization and Chen-Fox-Lyndon theorem pages: (1) the first factor of the Lyndon factorization of a nonempty word is its longest Lyndon prefix; (2) the start indices of the factors of a word are exactly the indices such that for every .
Lemma 1. For each , the longest Lyndon word that starts at has length .
Proof. Let . A Lyndon word starting at is a Lyndon prefix of , so by (1) the longest one is the first factor of the factorization of , and its length is the start of the second factor (or if there is one factor). The suffixes of are , compared as suffixes of . By (2), the second factor of starts at the least such that for all . Let be the least with , or if there is none. For , , so the minimum of is for each . Hence an index is not a factor start, because , and is a factor start if , because is smaller than the minimum . So the second factor starts at , and . If , then has one factor, of length .
Stack invariant. At the start of the iteration of line L3 for (and, for , at the end of the loop), the stack holds exactly the set
ordered with the smallest index on top. For both in , the definition with gives , so the ranks decrease from the top down. Also for every .
Initialization. For , is empty, and so is the stack.
Maintenance. First, when : every strictly between and has . Lines L4 and L5 pop the elements of rank larger than . Since ranks decrease from the top down, these form a top segment of the stack, and the pops stop at the first element with a smaller rank, or at the empty stack. Each element of with has , by the choice of , and is popped; itself has a smaller rank and stops the pops. So after the pops the top is , or the stack is empty and . Lines L6 and L7 set . After line L8, the stack holds on top of the elements of with rank smaller than . This set is : an index is in exactly when it is in and , and is in with nothing between. The smallest index, , is on top.
Termination. The loop runs times; each pop removes an element pushed once, so there are at most pops in total.
Conclusion for LYNDON-ARRAY. At the end, for every , which by Lemma 1 is the length of the longest Lyndon word that starts at .
FACTORS. By (1), the first factor of the factorization of is . If is the factorization, then is a nonincreasing product of Lyndon words, so by uniqueness it is the factorization of . By induction on , lines L12 and L13 list the start indices of all the factors, and the loop stops because .