1

Does the following algorithm have a complexity of O(nlogn)?

The thing that confuses me is that this algorithm divides twice, not once as a regular O(nlogn) algorithm, and each time it does O(n) work.

def equivalent(a, b):

    if isEqual(a, b):
        return True

    half = int(len(a) / 2)
    if 2*half != len(a):
        return False

    if (equivalent(a[:half], b[:half]) and equivalent(a[half:], b[half:])):
        return True

    if (equivalent(a[:half], b[half:]) and equivalent(a[half:], b[:half])):
        return True

    return False

2 Answers 2

7

Each of the 4 recursive calls to equivalent reduces the amount of input data by a factor of 2. Thus, assuming that a and b have the same length, and isEqual has linear time complexity, we can construct the recurrence relation for the overall complexity:

enter image description here

Where C is some constant. We can solve this relation by repeatedly substituting and spotting a pattern:

enter image description here

What is the upper limit of the summation, m? The stopping condition occurs when len(a) is odd. That may be anywhere between N and 1, depending on the prime decomposition of N. In the worse case scenario, N is a power of 2, so the function recurses until len(a) = 1, i.e.

enter image description here

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

2 Comments

Thanks, that helped me a lot, could you give me a reference to learn how to find the comlexity
@ayman for recursive functions the first step is always to find the recurrence relation. Once you have that you can make a range of different substitutions. If the relation is of the form T(n) = aT(n/b) + f(n), which is surprisingly common, then you can use the master theorem.
2

To enhance the above answer, there is a direct way to calculate with 'Master Method'. The master method works only for following type of recurrences.

T(n) = aT(n/b) + f(n) where a >= 1 and b > 1

We have three cases based on the f(n) as below and reduction for them:

  1. If f(n) = Θ(nc) where c < Logba then T(n) = Θ(n Logba)

  2. If f(n) = Θ(nc) where c = Logba then T(n) = Θ(nc Log n)

  3. If f(n) = Θ(nc) where c > Logba then T(n) = Θ(f(n)) = Θ(nc)

In your case,

we have a = 4, b = 2, c = 1 and c < Logba

i.e. 1 < log24

Hence => case 1

Therefore: T(n) = Θ(nLogba)

T(n) = Θ(nLog24)

T(n) = Θ(n2)

More details with examples can be found in wiki.

Hope it helps!

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.