0

I have this function:

def rec(lst):
    n = len(lst)
    if n <= 1:
        return 1
    return rec(lst[n // 2:]) + rec(lst[:n // 2])

How can I find the time complexity of this function?

1 Answer 1

1

Usually in such problems drawing the recursion tree helps.

enter image description here

Look at this photo I added, note how each level sums up to N (since slicing is the thing here doing the work), and the depth of the tree is logN (this is easy to show, since we divide by 2 each time, you can find an explanation here). So what we have is the function doing O(n) n*logn times which means in total we have O(n*logn).

Now another way of understanding this is using the "Master Theorem" (I encourage you to look it up and learn about it) We have here T(n) = 2T(n/2) + O(n), so according to the theorem a=2, b=2 so log_b(a) is equal to 1, and therefore we have (according to the 2nd case of the theorem):

T(n)=O(logn*(n**(log_b(a)))=O(nlogn)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.