Combine two stacks to preserve first-in, first-out queue order.
Use the editor below to process queue operations.
Use only stack operations
Separate newly pushed values from values ready to leave. Interleaved pushes, peeks, pops, and empty checks must preserve first-in, first-out order.
Submit your implementation when it passes the examples.
Process queue operations using only stack-style push and pop behavior internally.
Return one output per operation. Constructor and push produce null; pop and peek return values; empty returns a boolean.
At most 100 operations are performed.Results appear here after a run.
Push new values onto an input stack. When a front value is needed and the output stack is empty, move every input value to the output stack.
For pushes 1, 2, the first pop transfers both values, then returns 1. Push 3 into the input stack. The output stack still has 2, so the next peek must read 2. Moving 3 now would put it ahead of an older item. Transfer again only when the output stack is empty.
function runQueueUsingStacks(operations, values) {
class MyQueue {
constructor() {
this.input = [];
this.output = [];
}
moveIfNeeded() {
if (this.output.length > 0) return;
while (this.input.length > 0) {
this.output.push(this.input.pop());
}
}
push(value) {
this.input.push(value);
}
pop() {
this.moveIfNeeded();
return this.output.pop();
}
peek() {
this.moveIfNeeded();
return this.output[this.output.length - 1];
}
empty() {
return this.input.length === 0 && this.output.length === 0;
}
}
let queue;
const output = [];
for (let index = 0; index < operations.length; index++) {
const operation = operations[index];
if (operation === "MyQueue") {
queue = new MyQueue();
output.push(null);
} else if (operation === "push") {
queue.push(values[index][0]);
output.push(null);
} else {
output.push(queue[operation]());
}
}
return output;
}| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(n) | Across n operations, each value transfers at most once. One pop or peek can take O(n), but the amortized cost is O(1) per operation. |
| Auxiliary space | O(n) | The two stacks together store all queued values. |