3.8.7 · D3String Algorithms

Worked examples — Suffix array — construction O(n log n), LCP array

2,389 words11 min readBack to topic

This is the hands-on companion to the parent Suffix-Array note. The parent built the machinery; here we run that machinery across every kind of input a problem can hand you — including the weird degenerate ones that break naive code.


The scenario matrix

Every string you will ever feed a suffix array falls into one of these cells. The final column names the example that pins it down.

Cell Scenario class What could break Example
A Generic mixed string prefix-doubling rounds, sentinel Ex 1 (mississippi)
B All characters equal (aaaa) every suffix shares a prefix; LCP is a staircase Ex 2
C All characters distinct (abcd) first round already finishes; LCP all zero Ex 3
D Length 1 (a) one suffix, no adjacent pair, no LCP entry Ex 4
E Empty string () loops must not run; array is empty Ex 4
F Kasai "drop by at most 1" reuse resetting wrongly → Ex 5
G Word problem — pattern search binary-search block must be contiguous Ex 6
H Counting distinct substrings via LCP off-by-one in the two sums Ex 7
I Exam twist — two suffixes' LCP via RMQ LCP of non-adjacent pair needs a range-min Ex 8

Cells A–I are all covered below. Let us walk them.


Ex 1 — Cell A: a generic string, full doubling


Ex 2 — Cell B: all characters equal


Ex 3 — Cell C: all characters distinct


Ex 4 — Cells D & E: length 1 and empty (degenerate)


Ex 5 — Cell F: watching Kasai's "drop by at most 1" reuse



Ex 7 — Cell H: counting distinct substrings (formula drill)


Ex 8 — Cell I: exam twist, LCP of two non-adjacent suffixes


Recap

Recall Which cell did each example cover?

Ex 1 ::: A — generic string, full prefix-doubling Ex 2 ::: B — all equal characters (staircase LCP) Ex 3 ::: C — all distinct (one round, zero LCP) Ex 4 ::: D and E — length 1 and empty string Ex 5 ::: F — Kasai's carry-over of , drop-by-1 Ex 6 ::: G — pattern search via contiguous block Ex 7 ::: H — distinct-substring counting formula Ex 8 ::: I — LCP of non-adjacent suffixes via RMQ

Related tools worth revisiting: Radix Sort and Counting Sort (fast per-round sorting), Suffix Tree (the heavier cousin), Z-Algorithm and KMP (single-pattern alternatives), and Burrows–Wheeler Transform (built directly from the sorted-suffix order).