Interview Question
Share Lesson

Max Min Stack

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 base implementation 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.

 

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.

 

Breakdown

Loading...
Follow teacher
Share:

Table of Contents

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.

Loading...
Follow teacher
Share:

Table of Contents

Test Results

Run your code and see results here...

class MaxMinStack {
  // 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)
  }
}
// Upgrade for full course access
// Upgrade for full course access

Max Min Stack

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

 

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 MaxMinStack {
  // 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)
  }
}
// Upgrade for full course access
// Upgrade for full course access