Community

Start a Thread


Notifications
Subscribe You’re not receiving notifications from this thread.

Implement a Stack With Minimum (Main Thread)

Here is the interview question prompt, presented for reference.

Recall that a stack is an abstract data type modeling a collection of elements. Its primary operations are push (which adds an element to the top of the stack) and pop (which removes the most newest element).

Traditionally, a stack can easily be implemented in many dynamic languages using an array (and its built-in methods).

const stack = [];

stack.push(5);
stack.push(6);
stack.push(7);
stack.pop();
// 7
stack.pop();
// 6
stack = []

stack.append(5)
stack.append(6)
stack.append(7)
print(stack.pop())
# 7
print(stack.pop())
# 6
Stack<Integer> stack = new Stack<>();

stack.push(5);
stack.push(6);
stack.push(7);
System.out.println(stack.pop());
// Output: 7
System.out.println(stack.pop());
// Output: 6
std::stack<int> stack;

stack.push(5);
stack.push(6);
stack.push(7);
std::cout << stack.top(); stack.pop();  // Prints 7
// Output: 7
std::cout << stack.top(); stack.pop();  // Prints 6
// Output: 6
Stack<int> stack = new Stack<int>();

stack.Push(5);
stack.Push(6);
stack.Push(7);
Console.WriteLine(stack.Pop());
// Output: 7
Console.WriteLine(stack.Pop());
// Output: 6
stack := []int{}

stack = append(stack, 5)
stack = append(stack, 6)
stack = append(stack, 7)
fmt.Println(stack[len(stack)-1])  // Prints 7. 
stack = stack[:len(stack)-1]  // pops the top(the last) element
// Output: 7
fmt.Println(stack[len(stack)-1])  // Prints 6. 
stack = stack[:len(stack)-1]  // pops the top(the last) element
// Output: 6

However, let's say we wanted to implement a stack with the following interface, requiring the following methods to be defined. The most important being the last one, min() - a method that lets us obtain the minimum element at any given time.

push(val) - add an element on to the top of the stack.

pop(val) - remove the element at the top of the stack and return it.

peek(val) - see the element at the top of the stack without removing it.

min() - get minimum element in stack.

How would you do it, and can you implement it via a MinStack class? The class should have the following methods. Work off this skeleton:

class MinStack {
  constructor() {
  }

  push(val) {
  }

  pop() {
  }

  peek() {
  }

  min() {
  }
}

Can you do call min() and retrieve it in O(1) time?

Constraints

  • Total number of operations in the stack <= 100000
  • The values will be in the range -1000000000 and 1000000000
  • Expected time complexity : O(1)
  • Expected space complexity : O(n)

You can see the full challenge with visuals at this link.

Challenges • Asked almost 7 years ago by Jake from AlgoDaily

Jake from AlgoDaily Commented on Nov 30, 2017:

This is the main discussion thread generated for Implement a Stack With Minimum.