Implement a first-in-first-out queue using only two stacks, supporting push, pop, peek and empty. Input is a LeetCode-style list of operations.
Push onto an inbox stack. When you need the front and the outbox is empty, pour the whole inbox into the outbox, which reverses the order. Each element moves at most once.
1class MyQueue {2inbox: number[] = []; outbox: number[] = [];3push(x: number): void { this.inbox.push(x); }4private shift(): void {5if (!this.outbox.length)6while (this.inbox.length) this.outbox.push(this.inbox.pop()!);7}8pop(): number { this.shift(); return this.outbox.pop()!; }9peek(): number { this.shift(); return this.outbox.at(-1)!; }10empty(): boolean { return !this.inbox.length && !this.outbox.length; }11}
Create inbox and outbox.
Space: play/pause · ←/→: step