edited by
31,011 views
80 votes
80 votes

Consider the following operation along with Enqueue and Dequeue operations on queues, where $k$ is a global parameter.

MultiDequeue(Q){
    m = k
    while (Q is not empty) and (m > 0) {
        Dequeue(Q)
        m = m – 1
    }
}

What is the worst case time complexity of a sequence of $n$ queue operations on an initially empty
queue?

  1. $Θ(n)$
  2. $Θ(n + k)$
  3. $Θ(nk)$
  4. $Θ(n^2)$
edited by

9 Answers

Best answer
136 votes
136 votes
There are three possible operations on queue- Enqueue, Dequeue and MultiDequeue. MultiDequeue is calling Dequeue multiple times based on a global variable $k$. Since, the queue is initially empty, whatever be the order of these operations, there cannot be more number of Dequeue operations than Enqueue operations. Hence, the total number operations will be $n$ only.

Correct Answer: $A$
edited by
32 votes
32 votes
Initially the queue is empty and we have to perform n operations. i) One option is to perform all Enqueue operation s i.e. n Enqueue operations. Complexity will beθ(n) or ii) We can perform a mix of Enqueue and Dequeue operations. It can be Enqueue for first n/2 times and then Dequeue for next n/2, or Enqueue and Dequeue alternately, or any permutation of Enqueues and Dequeues totaling ‘n’ times. Complexity will be θ(n) or iii) We can perform Enqueues and MultiDequeues. A general pattern could be as follows: Enqueue Enqueue ... (ktimes) MultiDequeue Enqueue Enqueue ... (ktimes) MultiDequeue ... Up to total n ---- k items enqueued -----k items deleted----k i tems enqueued ----k items deleted -- and so on. The number of times this k-Enqueues, MutiDequeue cycle is performed So, Complexity will be k times Enqueue + 1 MultiD equeue) =n or iv) We can just perform n MultiDequeues (or n Dequeues for that matter): Each time the while condition is false (empty que ue), condition is checked just once for each of the ‘n’ operations. So θ(n).
26 votes
26 votes
the answer will be A , i.e theta(n)

explanation : if you read the question closely , they have said that Queue is initially empty . So , when the line "While(Q is not empty)" is checked it turns out to be false and nothing is done by " Multi-Dequeue(Q) " , hence constant time or theta(1) . According to the question , this operation is performed for n times , thus n * theta(1) = theta(n)

hope i was clear enough
7 votes
7 votes
initially queue is empty and hence while loop will never going to be executed and therefore time complexity is not going to be depend on k, and thus it will be only O(n).
Answer:

Related questions

52 votes
52 votes
9 answers
2
27 votes
27 votes
2 answers
3