Skip to problem
←

Implement Two Stacks in One Array

Easy 0 attempts

Implement two independent LIFO stacks using one array with total capacity n. The stacks share all available slots: either stack may use the entire capacity when the other is empty.

Expose push1(x), push2(x), pop1(), and pop2(). A push when the combined element count equals n does nothing. A pop from an empty stack returns -1; otherwise it removes and returns the most recently pushed value from that stack. Freed slots must be reusable by either stack.

Function contract

Construct TwoStacks(n), where n is the total capacity shared by both stacks. Each fixture supplies [n] and method calls on a fresh instance.

Output: push1 and push2 have no return value, including when full. pop1 and pop2 remove and return their stack’s top value, or -1 if empty. Undefined results display as null.

Example 1

Input
constructorArgs = [3]
operations = [["push1",1],["push2",2],["push1",3],["pop1"],["pop2"],["pop2"]]
Output
[null,null,null,3,2,-1]

Example 2

Input
constructorArgs = [1]
operations = [["push1",1],["push2",2],["pop2"],["pop1"]]
Output
[null,null,-1,1]
Constraints
  • 1 <= n <= 100
  • Each pushed value is a JavaScript safe integer.
Topics

Two-End Approach

Stack 1 grows from left, Stack 2 grows from right.

javascript
class TwoStacks {
  constructor(n) {
    this.arr = new Array(n);
    this.top1 = -1;
    this.top2 = n;
    this.size = n;
  }
  push1(x) {
    if (this.top1 < this.top2 - 1) this.arr[++this.top1] = x;
  }
  push2(x) {
    if (this.top1 < this.top2 - 1) this.arr[--this.top2] = x;
  }
  pop1() {
    return this.top1 >= 0 ? this.arr[this.top1--] : -1;
  }
  pop2() {
    return this.top2 < this.size ? this.arr[this.top2++] : -1;
  }
}

Time: O(1) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript