That's pretty neat. Your recursive approach hurts my head.
I have trouble analyzing the runtime of recursive algorithms like this.
I want to say that it is
I base this on the idea that a run of size m,n takes:
Not particularly confident in that though.
I did add a particularly pathological test however, and yours doesn't seem to manage it in a reasonable time
This leads to the recursive problem definition:
The algorithm ends up fairly straight forward from there just filling in the table row by row:
The pathological test is added at the bottom.
Mine results in:
I have trouble analyzing the runtime of recursive algorithms like this.
I want to say that it is
O(n^m)
but I'm not positive.I base this on the idea that a run of size m,n takes:
T(m,n) = O(n) * T(m-1, n-1)
Not particularly confident in that though.
I did add a particularly pathological test however, and yours doesn't seem to manage it in a reasonable time
Output:...
----------------------------------------------------------------------
Ran 3 tests in 346.731s
My approach went the dynamic programming route.T[i, j]
is the number of times needle[:i+1]
occurs as a subsequence of haystack[:j+1]
where T
is our dynamic programming table.This leads to the recursive problem definition:
T[i,j] = T[i,j-1] + T[i-1,j-1] if needle[i] == haystack[j] else T[i,j-1]
The algorithm ends up fairly straight forward from there just filling in the table row by row:
The pathological test is added at the bottom.
Mine results in:
Output:...
----------------------------------------------------------------------
Ran 3 tests in 0.003s
OK