Data Structures & AlgorithmsHardProduct company OA

A stack is built from two queues with a costly push: enqueue x into the empty queue Q2, move every element of Q1 into Q2 one by one, then swap the names Q1 and Q2. Counting each enqueue and each dequeue as one operation, how many operations does the 5th push cost (after four pushes and no pops)?

  1. A. 5
  2. B. 9
  3. C. 8
  4. D. 4

Correct answer: B. 9

Q1 holds 4 elements. The push does 1 enqueue of x plus, for each of the 4 old elements, 1 dequeue and 1 enqueue: 1 + 2·4 = 9. This keeps the newest element at the front of Q1, so pop is a single dequeue. '5' counts only enqueues; '8' forgets the enqueue of x.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic