Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to figure out the run time of my function

I have this python code for finding the longest substring. I'm trying to figure out the asymptotic run time of it and I've arrived at an answer but I'm not sure if it's correct. Here is the code:

def longest_substring(s, t):
    best = ' '
    for s_start in range(0, len(s)):
        for s_end in range(s_start, len(s)+1):
            for t_start in range(0, len(t)):
                for t_end in range(t_start, len(t)+1):
                    if s[s_start:s_end] == t[t_start:t_end]:
                        current = s[s_start:s_end]
                            if len(current) > len(best):
                                best = current
    return best

Obviously this function has a very slow run time. It was designed that way. My approach was that because there is a for loop with 3 more nested for-loops, the run-time is something like O(n^4). I am not sure if this is correct due to not every loop iterating over the input size. Also, it is to be assumed that s = t = n(input size). Any ideas?

like image 241
donut juice Avatar asked Jan 19 '26 11:01

donut juice


1 Answers

If you're not convinced that it's O(n^5), try calculating how many loops you run through for string s alone (i.e. the outer two loops). When s_start == 0, the inner loop runs n + 1 times; when s_start == 1, the inner loop runs n times, and so on, until s_start = n - 1, for which the inner loop runs twice.

The sum

(n + 1) + (n) + (n - 1) + ... + 2

is an arithmetic series for which the formula is

((n + 1) + 2) * n / 2

which is O(n^2).

An additional n factor comes from s[s_start:s_end] == t[t_start:t_end], which is O(n).

like image 79
univerio Avatar answered Jan 21 '26 00:01

univerio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!