Prefix array
A prefix array of a string is an array such that is the length of the longest prefix of that is also a prefix of .
Algorithm
The following brute-force algorithm computes a prefix array of a string.
:{
import Data.List
-- | Length of the longest common prefix.
llcp :: (Eq a) => [a] -> [a] -> Int
llcp [] ys = 0
llcp xs [] = 0
llcp (x : xs) (y : ys) = if x == y then 1 + llcp xs ys else 0
naivePrefix :: (Eq a) => [a] -> [Int]
naivePrefix xs = map (llcp xs) (tails xs)
:}
naivePrefix "aabcaabxaaz"
naivePrefix "aabaabaabbaaa"
naivePrefix "anpanman"
naivePrefix "abacabacab"This algorithm is
; llcp xs takes linear time, and
tails produces a list of lists that scales
quadratically with the size of xs.
The key insight comes when we observe the algebraic behaviour of
llcp. Let
be lists such that
,
. We then have the following formula for
.
let (us, vs, ws) = ("aab", "aac", "abc")
llcp us vs
llcp vs ws2
1