I would like to know what's the complexity of the following algorithm and, most importantly, the step by step process which leads to deducing it.
I suspect it's O(length(text)^2*length(pattern)) but I have trouble solving the recurrence equation.
How would the complexity improve when doing memoization (i.e. dynamic programming) on the recursive calls?
Also, I would appreciate pointers to techniques/books which would help me learn how to analyze this kind of algorithms.
In Python:
def count_matches(text, pattern):
if len(pattern) == 0: return 1
result = 0
for i in xrange(len(text)):
if (text[i] == pattern[0]):
# repeat the operation with the remaining string a pattern
result += count_matches(text[i+1:], pattern[1:])
return result
In C:
int count_matches(const char text[], int text_size,
const char pattern[], int pattern_size) {
if (pattern_size == 0) return 1;
int result = 0;
for (int i = 0; i < text_size; i++) {
if (text[i] == pattern[0])
/* repeat the operation with the remaining string a pattern */
result += count_matches(text+i, text_size-(i+1),
pattern+i, pattern_size-(i+1));
}
return result;
}
Note: The algorithm intentionally repeats the matching for every substring. Please don't focus in what kind of matching the algorithm is performing, just on its complexity.
Apologies for the (now fixed) typos in the algorithms