Hone logo
Hone
Problems

Stack with Minimum in JavaScript

This challenge asks you to implement a Stack data structure with an additional getMin() method that efficiently returns the minimum element currently in the stack. A stack with minimum functionality is useful in scenarios where you need to track both the overall state of a stack and its minimum value simultaneously, such as in financial applications or monitoring systems.

Problem Description

You are to implement a MinStack class in JavaScript. This class should behave like a standard stack, supporting push, pop, and top operations. In addition, it must provide a getMin() method that returns the minimum element currently in the stack in O(1) time.

Key Requirements:

  • push(val): Pushes the element val onto the top of the stack.
  • pop(): Removes the element on top of the stack and returns that element.
  • top(): Returns the element on the top of the stack without removing it.
  • getMin(): Returns the minimum element in the stack.

Expected Behavior:

The getMin() method should always return the smallest element currently present in the stack. If the stack is empty, getMin() should return undefined. The push, pop, and top methods should behave as expected for a standard stack.

Edge Cases to Consider:

  • Empty stack: Handle cases where the stack is empty for pop, top, and getMin.
  • Duplicate minimums: The minimum value might appear multiple times in the stack.
  • Negative numbers: The stack can contain negative numbers.
  • Large numbers: Consider potential overflow issues if dealing with very large numbers (though this is less of a concern in JavaScript).

Examples

Example 1:

Input:
push(2);
push(0);
push(3);
getMin();
pop();
getMin();

Output:

0
0

Explanation: The stack initially contains [2, 0, 3]. getMin() returns 0. pop() removes 3, leaving [2, 0]. getMin() again returns 0.

Example 2:

Input:
push(-2);
push(0);
push(-3);
getMin();
pop();
getMin();

Output:

-3
-2

Explanation: The stack initially contains [-2, 0, -3]. getMin() returns -3. pop() removes -3, leaving [-2, 0]. getMin() returns -2.

Example 3: (Edge Case - Empty Stack)

Input:
getMin();

Output:

undefined

Explanation: The stack is empty. getMin() returns undefined.

Constraints

  • The number of operations (push, pop, top, getMin) will be between 1 and 100,000.
  • The values pushed onto the stack will be integers within the range of -10<sup>4</sup> to 10<sup>4</sup>.
  • The time complexity of getMin() must be O(1).
  • The space complexity of your solution should be O(n), where n is the number of elements in the stack.

Notes

Consider using an auxiliary data structure to efficiently track the minimum element. A simple array can be used to store the minimum value at each point in the stack's history. Think about how to update this auxiliary structure whenever a new element is pushed or an element is popped. Focus on achieving O(1) time complexity for getMin().

Loading editor...
javascript