# Suffix Arrays, Adjacent LCPs, and Expectation Problem setter's solution: count distinct and unique substrings using a suffix array and LCPs. Codex (GPT-6): integer doubling sort, expectation derivation, 64-bit queries, noninvertible-denominator handling, and verification. The primary program is [std.cpp](std.cpp); a complete [suffix automaton solution](solution-alternative.en.md) is available as [alternative.cpp](alternative.cpp). ## From Counts to Expectation Let $D$ be the number of distinct nonempty substrings and $U$ the number occurring exactly once. The whole string occurs once, so $U\ge1$ . Each trial succeeds with probability $p=U/D$ . The number of trials until the next success is geometric with expectation $1/p$ . The wait for $N$ successes is the sum of $N$ such waits. Linearity of expectation gives $ND/U$ . The final successful trial is included; do not subtract one. For $N=0$ , the answer is zero. ## Two Suffix-Array Formulas Sort all suffixes lexicographically. Let $L_i$ be the length of suffix $i$ in this order, and let $h_i$ be its longest common prefix with its predecessor. Set $h_0=h_n=0$ . $$D=\sum_{i=0}^{n-1}(L_i-h_i),\qquad U=\sum_{i=0}^{n-1}\bigl(L_i-\max(h_i,h_{i+1})\bigr).$$ Suffixes sharing a prefix form a contiguous interval. Thus the prefixes of suffix $i$ already represented by earlier suffixes are exactly those of length at most $h_i$ , proving the formula for $D$ . To test occurrence at any other position, only the two neighboring suffixes matter. If a farther suffix shares a prefix, the intervening adjacent suffix also shares it. Hence the longest repeated prefix has length $\max(h_i,h_{i+1})$ . Longer prefixes occur once and cannot be counted at another suffix, proving the formula for $U$ . Overlapping occurrences still have different suffix starts and are handled normally. Build the suffix array by integer rank doubling and two stable counting sorts per round. A linear LCP scan computes neighboring common prefixes. Integer ranks provide exact comparisons without floating-point ranking. ## Modular Fractions If $P\nmid U$ , compute $(N\bmod P)(D\bmod P)U^{-1}\bmod P$ . If $P\mid U$ , the bound $1\le U\le n(n+1)/2