Challenge - 5 Problems
Queue Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of enqueue and dequeue operations
What is the output of the following code that uses two stacks to implement a queue?
DSA C++
class QueueUsingStacks { private: std::stack<int> s1, s2; public: void enqueue(int x) { s1.push(x); } int dequeue() { if (s2.empty()) { while (!s1.empty()) { s2.push(s1.top()); s1.pop(); } } int val = s2.top(); s2.pop(); return val; } }; int main() { QueueUsingStacks q; q.enqueue(10); q.enqueue(20); int a = q.dequeue(); q.enqueue(30); int b = q.dequeue(); int c = q.dequeue(); std::cout << a << " " << b << " " << c << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Remember that dequeue transfers elements from s1 to s2 only when s2 is empty.
✗ Incorrect
The queue enqueues 10 and 20. The first dequeue moves 10 and 20 to s2 and pops 10. Then 30 is enqueued to s1. The second dequeue pops 20 from s2. The third dequeue moves 30 from s1 to s2 and pops 30.
🧠 Conceptual
intermediateTime complexity of dequeue operation
What is the amortized time complexity of the dequeue operation in a queue implemented using two stacks?
Attempts:
2 left
💡 Hint
Consider how often elements are moved between stacks.
✗ Incorrect
Each element is moved at most twice: once when pushed to s1 and once when moved to s2. So amortized dequeue is O(1).
🔧 Debug
advancedIdentify the error in dequeue method
What error will occur when running this dequeue method if both stacks are empty?
DSA C++
int dequeue() { if (s2.empty()) { while (!s1.empty()) { s2.push(s1.top()); s1.pop(); } } int val = s2.top(); s2.pop(); return val; }
Attempts:
2 left
💡 Hint
What happens if s2.top() is called when s2 is empty?
✗ Incorrect
Calling top() on an empty stack causes undefined behavior, often a segmentation fault.
❓ Predict Output
advancedState of stacks after operations
After executing the following operations on a queue implemented with two stacks, what is the content of s1 and s2 (top to bottom)?
DSA C++
QueueUsingStacks q; q.enqueue(1); q.enqueue(2); q.enqueue(3); q.dequeue(); q.enqueue(4); // What are s1 and s2 now?
Attempts:
2 left
💡 Hint
Dequeue moves elements from s1 to s2 only if s2 is empty.
✗ Incorrect
Enqueues 1,2,3 put 3 (top), 2, 1 (bottom) in s1. Dequeue transfers to s2: push 3 (bottom), push 2, push 1 (top), then pops 1, leaving s2: 2 (top), 3. Enqueue 4 puts 4 (top) in s1.
🧠 Conceptual
expertWhy use two stacks to implement a queue?
Which of the following best explains why two stacks can be used to implement a queue?
Attempts:
2 left
💡 Hint
Think about how stack order is reversed.
✗ Incorrect
Two stacks reverse the order of elements twice, so the first element enqueued is the first dequeued, mimicking a queue.
