Skip to the workspace
Pebellslearn by building
String Algorithms  ›  Lesson

Suffix Arrays & the Longest Repeat

Suffix Arrays 28 minSorted suffixes put anything alike next to each other; the LCP array measures exactly how alike

dsa / Suffix Arrays & the Longest Repeat

Explore each scene at your own pace.

01 · Sorting suffixes instead of comparing substrings

Sorting suffixes instead of comparing substrings

Suffix Arrays & the Longest Repeat

Definition
A suffix array lists the starting positions of all the suffixes of a string in alphabetical order of those suffixes. The LCP array stores how many leading characters each suffix shares with its neighbour, which reveals repeated substrings.
In plain words
Write out every ending of a word, sort them like dictionary entries, and similar endings end up side by side. Counting how many letters each neighbouring pair shares shows at once which piece of text repeats the most.

In short: a suffix array is every suffix of a string, sorted alphabetically — stored as just their starting indices, not copies of the text. Once sorted, two suffixes that share a long prefix sit next to each other, because sorting groups anything alike. The LCP array (longest common prefix) measures exactly how much each neighbouring pair shares. Together they turn "does this substring repeat, and how much" from a scan-everything question into a read-the-neighbours question.

A sorted list of banana's six suffixes stacked vertically, with the shared-letter count written in the gap between each pair, the biggest gap between ana and anana highlighted

Sorting suffixes instead of comparing substrings

"banana" has 6 suffixes: banana, anana, nana, ana, na, a. Sorted alphabetically:

python

The array stores indices, [5, 3, 1, 0, 4, 2], not the suffix strings themselves — slicing s[i:] is only for printing. Building it this way, by sorting Python string slices, is O(n² log n) in the worst case (each comparison can itself cost O(n)), fine for a lesson-sized string; production suffix-array builders use O(n log n) radix-style construction, which is past this lesson's scope.

Scene 1 of 6
Project context and further resources
You're building a piece ofQuarry — the text index
This piece — longest_repeated_substring(): Sorts every suffix of a document to find its longest repeated chunk without scanning every substring pair.
Scenario Quarry's text index flags the longest chunk of a document that repeats somewhere else in it, to catch copy-pasted boilerplate before it's indexed twice.
longest_repeated_substring.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
longest_repeated_substring(s) → strThe longest substring that occurs more than once, or "" if nothing repeats.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.