Definition
Prefix Function
The prefix function of a string records the length of the longest proper border of each prefix of :
Stop at index and consider only . Find the longest string appearing at both ends of this prefix, without taking the whole prefix itself. Its length is ; characters after play no part.
The bound excludes the whole prefix, whose length is . For , both slices mean the empty string, so when no non-empty proper border exists. Otherwise, is the length of the maximal non-trivial border of .
Why the Whole Prefix Is Excluded
Every prefix is a border of itself. Allowing that choice would give at every position, revealing nothing about repeated characters at its ends. Excluding it makes the function measure how much of the beginning reappears at the current end.
For , the inspected prefix contains one character. Its only proper border is , so . The empty string is a trivial border, not a non-trivial one.
How Much of a Match Can Be Kept
We want to find . The numbers are zero-based pattern indices.
We search in . These numbers are text indices; they stay fixed when the pattern moves.
Start at text position . The first five characters match, but disagrees with .
The Naïve Restart
The naïve approach shifts by one and starts again at . Position fails immediately. At position , it checks aba again before returning to text position .
What the Pattern Alone Tells Us
Set the text aside. The matched prefix has longest proper border aba, so . Its final three characters are already a copy of the pattern’s first three characters.
A shift of one would require baba to equal abab. It does not. The border therefore identifies the first possible restart: shift by and retain three matches. This information depends only on the pattern.
Use the Border to Keep the Match
Bring back the text. Its matched ababa equals the pattern prefix just inspected. Shift directly to position , keep aba without rechecking it, and compare with .
In general, after matches and a mismatch:
If this comparison also fails, follow the nested borders with for . Here gives possible starts , skipping starts and . These are candidates, not guaranteed matches. If even fails, advance the text position.
Examples
0 a0 1 ab0 2 aba1 3 abab2 4 ababa3 5 ababac0 6 ababaca1 At , the prefix equals the suffix . These occurrences overlap at index , which is allowed.
Appending changes the end: no non-empty proper prefix of ends in , so the border length falls from to . Appending the next gives a border of length .
0 a0 1 aa1 2 aaa2 3 aaaa3
0 a0 1 ab0 2 abc0 3 abca1 4 abcab2