Max Min Stack Coding Interview Question | Skilled.dev
Interview Question

Max Min Stack

Course launching November 17, 2020

Follow me on YouTube for free coding interview videos.

Users who sign up for the email list will receive an exclusive 75% discount at launch.

Your subscription could not be saved. Please try again.
Your subscription was successful! 🤓

We've already seen how to implement a stack using linked lists or dynamic arrays. Your challenge is going to be to build on this to create a stack with additional superpowers.

Create a MaxMinStack class that will return the maximum and minimum value from the stack at any time using getStackMax and getStackMin functions.

// Examples
[4] // max: 4, min: 4
// Push 5 more items
[4, 17, 4, 42, 0, 1] // max: 42, min: 0
// Pop 3 items
[4, 17, 4] // max: 17, min: 4
// Pop 2 items
[4] // max: 4, min: 4
// Push 2 items
[4, -10, -5] // max: 4, min: -10

You will start with the Stack class below. You can add or update any method necessary for this to work. The stack will only be passed integers.

class Stack {
  // Any of the initial methods can be updated
  constructor() {
    this.stack = [];
  }
  peek() {
    return this.stack[this.stack.length - 1];
  }
  push(item) {
    this.stack.push(item);
    return item;
  }
  pop() {
    return this.stack.pop();
  }

  // You must implement the methods below
  getStackMax() {
    // Return the largest integer currently in the stack (don't remove it)
  }
  getStackMin() {
    // Return the smallest integer currently in the stack (don't remove it)
  }
}

Validate My Answer

  1. A brute force solution would be to iterate the stack to track the max/min integer. This would require O(n) time, so we should be looking for solutions better than this.

  2. The max and min can increase or decrease at any point depending on what integer you push/pop. Make sure you account for this.

  3. You can solve this in O(1) time and O(n) space.