Question

Algorithm 1. QUEUESTUFF(n)
Input: Integer n
1) Let Q = an empty Queue
2) For i = 1 to n
3) Q.Enqueue(i)
4) End For
5) For i = 1 to n-1
6) Let X = Q.Dequeue()
7) End For
8) Let X = Q.Dequeue()
Output: The contents of X

What is the computational complexity O(n) for algorithm QUEUESTUFF?

The first For loop is just of n and the second nested one is of n-1. So would this make O(n):

O(2n-1) by just doing (n + n) - 1

or would it be O(n^2 - 1) by doing (n * n) - 1

Thanks for any help, I just wanted to clarify this. My guess is that because we have a nested For loop, we would have to times n by n-1, however I just thought that I could assure myself better by getting someone else opinion.

Was it helpful?

Solution

Got the answer thanks to Smoore. Since the loop is not nested, the Big-O would be O(2n-1).

OTHER TIPS

There are two independent (not nested) for loops. n items are enqueued and then n items are dequeued, giving a complexity of O(n) times the complexity of enqueueing or dequeueing. If queue-operation complexity is O(1), then the procedure's complexity is O(n), but if queue-operation complexity is O(ln n), then the procedure's complexity is O(n ln n).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top