Data Structures & AlgorithmsVery hardTCS NQT · Infosys pattern
A queue is implemented with two stacks (enqueue pushes to stack "in"; dequeue pops from stack "out", refilling "out" from "in" by popping/pushing when "out" is empty) and runs: enqueue(8), enqueue(5), enqueue(3), enqueue(4), dequeue(), dequeue(), dequeue(). In what order are values dequeued?
- A. 8, 5, 3
- B. 4
- C. 4, 3, 5
- D. 3, 5, 8
Correct answer: A. 8, 5, 3
Moving every element from "in" to "out" (which reverses their order) exactly when "out" runs empty restores FIFO order overall, so dequeues return 8, 5, 3 — the same order the values were enqueued in. Treating it as a single stack (LIFO) would wrongly give 4, 3, 5.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is the postfix (Reverse Polish) form of the infix expression "(c + i) a - j / d", built with the standard stack-based conversion (^…
- The Dutch National Flag algorithm (single pass, three pointers low/mid/high) partitions [1, 0, 1, 2, 2, 2, 1, 1] (values 0, 1, 2 only) in…
- Elevation map [6, 1, 1, 0, 3, 3, 5, 5, 2, 0] (bar width 1). Using the two-pointer / prefix-max approach for trapping rain water, how much…
- Array [75, 79, 80, 82, 6, 11, 23, 40, 63, 67] is a sorted array rotated at pivot 6. Using the standard O(log n) rotated-array binary…
- Array [1, 2, 3, 4, 5, 6, 7, 8] is left-rotated by d = 7 positions using the reversal algorithm (reverse first d, reverse rest, reverse…
- What is the sum of the minimum element over every contiguous subarray of [7, 6, 6, 4, 8, 9]?