JS Built-ins
Algorithmsadvanced

Stack-based Min Tracker

πŸ“– Usage Example
class MinStack {
  constructor() { this.stack = []; this.mins = []; }
  push(v) {
    this.stack.push(v);
    this.mins.push(Math.min(v, this.mins.at(-1) ?? v));
  }
  min() { return this.mins.at(-1); }
}

Track minimums in O(1) by maintaining a parallel stack of running minimums.

Stack with Min Tracking

Design a Stack that supports pushing, popping, and tracking the minimum element efficiently in O(1) time.

Challenge: Without auxiliary space, finding min is O(n). With a helper stack, it's O(1).

Operations:

  • push(x): Add element
  • pop(): Remove element
  • getMin(): Return current minimum in O(1)
class MinStack {
  push(x: number): void {}
  pop(): number | undefined {}
  getMin(): number | undefined {}
}

const ms = new MinStack()
ms.push(3)
ms.push(1)
ms.push(2)
ms.getMin() // 1
πŸ’‘ Hints (5)
  • β€’ Use two stacks: one for elements, one for minimums.
  • β€’ When pushing, check if it's less than or equal to the current min.
  • β€’ When popping, check if it was the current min and pop from minStack too.
  • β€’ getMin returns the top of the minStack.
  • β€’ This keeps getMin at O(1) instead of O(n).