AlgoTales · Roadmap

Prefix function / LPS

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

The prefix function records, for every position in a word, how long the longest ending of the text so far is that is also a beginning of the word. It sounds odd, but it is the memory that lets fast text searches avoid starting over after a mismatch.

Practical use cases

  • Web app: Detecting a repeated pattern in a string. A log viewer wants to tell the support team that an error message repeats like "retry-retry-retry". Computing the prefix table once shows the smallest repeating block: if the text length divides evenly by the block length, the whole string is just that block repeated. One pass over the text, no nested loops.
  • Web app: Fast "find in page" over big text. A document editor in the browser lets users search a 5 MB pasted text for a phrase. Restarting the comparison from the next letter after every miss wastes millions of checks. With a prefix table built from the phrase, the search never steps backward through the text, so highlighting arrives while the user is still typing.
  • System: Network and file scanners. A tool that scans uploaded files for a known signature has to read gigabytes. Using the prefix table of the signature, it reads every byte exactly once and still finds every match, which keeps scanning speed steady even when the file is full of almost-matching bytes.

The story: Zoya's Rangoli Border

Zoya was painting a long rangoli border in front of the house for Diwali, using the pattern ABABCABAB: two colours, a special C-coloured dot, then a repeat. Halfway through, a gust of wind smudged the paint. Starting over would waste hours.

"Wait," said Grandpa Bhaskar. "Look at what you have already painted. The last part of what you finished is the same as the very beginning of the border. So the beginning is already done for you at this spot. You need not go back to zero." Zoya looked: she had finished ABABCAB, and its ending AB was exactly the beginning AB.

Zoya made a chart for every position: "How much of the beginning is repeated as the ending up to here?" ABABCABAB gave 0, 0, 1, 2, 0, 1, 2, 3, 4. This chart is the prefix function, also called the LPS table (Longest Prefix which is also a Suffix). It is the secret memory that lets pattern matching recover from a mistake without starting over.

How to spot this problem, and where you need it

After every near-miss while matching a pattern you jump back and start comparing again from scratch, so repetitive text makes the search crawl, and you want to reuse what you already matched.

Signs you need it

  • Your matching code has a loop inside a loop where the inner one restarts from the next text position after each failure.
  • The problem mentions "border", "prefix that is also a suffix", "smallest repeating unit" or "period of a string".
  • Search is fast on normal sentences but terrible on repetitive inputs such as "aaaaaaab" or long runs of the same characters.

Where to use it in a project

  • The preparation step for KMP search used in find-in-page, log scanning or content filters.
  • Checking whether a string is made of one repeated chunk, for example validating repeated codes or tokens.
  • Spotting periodic patterns in sensor, signal or log text.

The solution

Build a small table once from the pattern. For each position, store how long the longest ending of the text so far is that also matches the beginning of the pattern. Fill it left to right, reusing earlier entries: when a new letter does not extend the match, fall back to the shorter border stored earlier instead of restarting. The table is later used to know exactly where to resume after a mismatch.

Payoff: Before: a worst-case search of a 100,000-character text with a 1,000-character pattern could cost around 100 million checks. After: roughly 100,000.

Explain it like I am 8

Look at the word you wrote so far. Does its tail look like its head? If the last two letters are the same as the first two letters, you do not need to rewrite them: you already have a head start. The LPS table just records how big that head start is at every spot.

How it works, step by step

  1. Start the table with 0 for the first letter: a one-letter word has no proper prefix that is also a suffix.
  2. Keep a counter k = how many letters of the pattern's start match the ending so far.
  3. For each next letter: if it matches p[k], increase k and record it.
  4. If it does not match and k is above 0, fall back: k = table[k - 1], and try again.
  5. If k reaches 0 and the letter still does not match the first letter, record 0.

The code in four languages

PHP

<?php
// LPS table: lps[i] = length of the longest proper prefix of p[0..i]
// that is also a suffix of p[0..i].
function lpsTable(string $p): array {
    $m = strlen($p);
    $lps = array_fill(0, $m, 0);
    $k = 0;                                   // length of the current matching border
    for ($i = 1; $i < $m; $i++) {
        while ($k > 0 && $p[$i] !== $p[$k]) {
            $k = $lps[$k - 1];                // fall back to a shorter border
        }
        if ($p[$i] === $p[$k]) {
            $k++;                             // border grows by one
        }
        $lps[$i] = $k;
    }
    return $lps;
}

echo implode(' ', lpsTable("ABABCABAB")) . "\n";    // 0 0 1 2 0 1 2 3 4
echo implode(' ', lpsTable("AAAA")) . "\n";         // 0 1 2 3

JavaScript

// LPS table: lps[i] = length of the longest proper prefix of p[0..i]
// that is also a suffix of p[0..i].
function lpsTable(p) {
  const m = p.length;
  const lps = new Array(m).fill(0);
  let k = 0;                                  // length of the current matching border
  for (let i = 1; i < m; i++) {
    while (k > 0 && p[i] !== p[k]) {
      k = lps[k - 1];                         // fall back to a shorter border
    }
    if (p[i] === p[k]) {
      k++;                                    // border grows by one
    }
    lps[i] = k;
  }
  return lps;
}

console.log(lpsTable('ABABCABAB').join(' '));    // 0 0 1 2 0 1 2 3 4
console.log(lpsTable('AAAA').join(' '));         // 0 1 2 3

Java

import java.util.*;

public class Main {
    // LPS table: lps[i] = length of the longest proper prefix of p[0..i]
    // that is also a suffix of p[0..i].
    static int[] lpsTable(String p) {
        int m = p.length();
        int[] lps = new int[m];
        int k = 0;                                // length of the current matching border
        for (int i = 1; i < m; i++) {
            while (k > 0 && p.charAt(i) != p.charAt(k)) {
                k = lps[k - 1];                   // fall back to a shorter border
            }
            if (p.charAt(i) == p.charAt(k)) {
                k++;                              // border grows by one
            }
            lps[i] = k;
        }
        return lps;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(lpsTable("ABABCABAB")));   // [0, 0, 1, 2, 0, 1, 2, 3, 4]
        System.out.println(Arrays.toString(lpsTable("AAAA")));        // [0, 1, 2, 3]
    }
}

Go

package main

import "fmt"

// lpsTable returns lps where lps[i] = length of the longest proper prefix of
// p[0..i] that is also a suffix of p[0..i].
func lpsTable(p string) []int {
	m := len(p)
	lps := make([]int, m)
	k := 0 // length of the current matching border
	for i := 1; i < m; i++ {
		for k > 0 && p[i] != p[k] {
			k = lps[k-1] // fall back to a shorter border
		}
		if p[i] == p[k] {
			k++ // border grows by one
		}
		lps[i] = k
	}
	return lps
}

func main() {
	fmt.Println(lpsTable("ABABCABAB")) // [0 0 1 2 0 1 2 3 4]
	fmt.Println(lpsTable("AAAA"))      // [0 1 2 3]
}

Time: O(m) · Extra space: O(m). Although there is a while loop inside the for loop, k can only fall as far as it has risen, so the total work stays linear in the pattern length m.

Watch out for

  • Counting the whole string as its own prefix and suffix. We only allow proper prefixes, shorter than the string itself.
  • Falling back with k = k - 1 instead of k = lps[k - 1]. The fallback must jump to the next shorter border, not just one step.
  • Starting the loop at 0 instead of 1: lps[0] is always 0.

Quick check

  1. What is lps for the whole pattern "AAAA"?
    • 4
    • 3
    • 0
  2. What does lps[i] = 2 mean?
    • The first 2 letters equal the last 2 letters up to i
    • Position i is the 2nd letter
    • The pattern repeats twice
  3. On a mismatch with k > 0, where does k go?
    • To 0
    • To k + 1
    • To lps[k - 1]