I’m currently learning algorithms from a book I have bought from Amazon but it is the worst book in the world, it shows examples but crucially doesn’t show how to work the answers out.
so the first question I have is,
Prefix-Match(T[1..n], P[1..m]) {
i := 1 // point to current position in T[]
while(i <= n) {
// find a match for first character of P
while( i <= n && T[i] != P[1]) i++
if (i > n) return; // quit
len := 1
// match as much as possible
while(len < m && i+len <= n && T[i+len] == P[1+len]) len++
output i, len
i++
}
what would the output of this program be if T = [a,b,a,b,c,a,b] and P = [a,b,a]???
and secondly how do I work out time complexity of the algorithm, in terms of m and n?
Well first of all a question: what book you are talking about? If this is exactly a code sample from it, then it has to be terrible…
And now for the answer:
whileloop),i = 1, becauseT[1] == P[1](if T does not contain the first element of P then the function simply returns),imatch subsequent elements inP(meaning that it will take elementT[i+1]and check if it matchesP[2]and same withT[i+2]andP[3]),iit found and how many matches it found.Basically this function finds all the subsets of T that match P. And the exact output should look like this:
Tldr: the first number is the index at which the element
P[1]is in the table T and the second number is the number of elements following it equal to its counterparts in table P.But I do not know what was the author’s intention – from what I understand the found subset doesn’t have to completely match the P set, i.e. if we took:
T = [a,c,a]andP = [a,b,a]we would still get the output1,3. There is no element that breaks the loop if the subsequent element of the found subset in T is different from its counterpart in P.About time complexity there’s plenty of articles on the web. If you want a book then CLRS Introduction to Algorithms or Algorithm Design Manual are my favorits.