Stacks and Queues
Queue from Two Stacks
Implement queue behavior with an input stack and an output stack.
Algorithm
Basic Implementation
basic.ts
function render(values: number[]) {
return values.join(" -> ");
}
const inStack: number[] = [];
const outStack: number[] = [];
for (const value of [10, 20, 30]) {
inStack.push(value);
}
while (inStack.length > 0) {
outStack.push(inStack.pop());
}
const removed: number[] = [];
while (outStack.length > 0) {
removed.push(outStack.pop());
}
console.log(render(removed));
Complexity
- Time: O(1) amortized per operation
- Space: O(n)
Implementation notes
- TypeScript declares
inStack,outStack, andremovedasnumber[], andrender(values: number[])formats numeric arrays. - Enqueue appends
10,20, and30withinStack.push(value), mutating the input stack from[]to[10, 20, 30]. - Transfer runs while
inStack.length > 0, usinginStack.pop()andoutStack.push(...). The transfer and removal loops are length-guarded, so the replay never observes anundefinedpop, though TypeScript's arraypop()type is still possiblyundefinedin stricter settings. - The transfer reverses order in the arrays:
inStack = [10, 20, 30],outStack = []becomesinStack = [],outStack = [30, 20, 10]. - The removal loop pops
outStackintoremoved, producingremoved = [10, 20, 30]andoutStack = [], which is the FIFO queue order. console.log(render(removed))prints10 -> 20 -> 30. Visible allocation is the short input literal, the three arrays, and the joined output string; mutation is limited topushandpopoperations.
input stack
Enqueue pushes new values onto the input stack.
output stack
When the output stack is empty, transferring all input values reverses them into dequeue order.