Project ForgeSign up free
Algorithms
Complexity Analysis
GATE 2013
Hard

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 (Enqueue, Dequeue and/or MultiDequeue) on an initially empty queue?

  • Θ(n)
  • BΘ(n + k)
  • CΘ(nk)
  • DΘ(n²)

Explanation

Each MultiDequeue call does at most k basic Dequeue steps, so a single call could naively look like O(k), suggesting O(nk) for n calls — but that overcounts: across the ENTIRE sequence of n operations, the total number of elements ever dequeued (via ordinary Dequeue or via MultiDequeue's internal loop) can never exceed the total number of elements ever enqueued, which is at most n. So the aggregate cost of all dequeue-style work across the whole sequence is O(n), and each Enqueue itself is O(1), giving an overall Θ(n) for the whole sequence — this is a classic amortized/aggregate-analysis argument, not a per-call worst case multiplied naively by n.

Source: GATE CS 2013 (2013)

This question is part of a 15-day revision cycle — sign in and Project Forge will bring it back the day before you'd forget it.

Start revising free