I was reading a book which tells that the outer loops time complexity is O(n-m) whereas for inner loop the books gives explanation as
” The inner while loop goes around at most m times, and potentially
far less when the pattern match fails. This, plus two other
statements, lies within the outer for loop. The outer loop goes around
at most n−m times, since no complete alignment is possible once we get
too far to the right of the text. The time complexity of nested loops
multiplies, so this gives a worst-case running time of O((n − m)(m +
2)). “
I didn’t understand for what reason the time complexity of inner loop is O(m+2) instead of O(m)? Please help.
int findmatch(char *p, char *t)
{
int i,j; /* counters */
int m, n; /* string lengths */
m = strlen(p);
n = strlen(t);
for (i=0; i<=(n-m); i=i+1) {
j=0;
while ((j<m) && (t[i+j]==p[j]))
j = j+1;
if (j == m) return(i);
}
return(-1);
}
The while loop:
is O(m), then you have +2 from (
other statements):