Leetcode 155: Min Stack

grid47
grid47
Exploring patterns and algorithms
Oct 22, 2024 6 min read

A stack where each layer gently illuminates, showing the minimum value glowing at the bottom.
Solution to LeetCode 155: Min Stack Problem

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Problem
Approach
Steps
Complexity
Input: The input consists of a sequence of operations performed on a MinStack object. Operations include push, pop, top, and getMin.
Example: [[], [-2], [0], [-3], [], [], [], []]
Constraints:
• -231 <= val <= 231 - 1
• pop, top, and getMin operations will always be called on non-empty stacks.
• At most 3 * 10^4 calls will be made to push, pop, top, and getMin.
Output: The output will be the results of the getMin, top, and pop operations, in sequence, as requested in the input.
Example: [null, null, null, null, -3, null, 0, -2]
Constraints:
• The result of each method call will be part of the output sequence.
Goal: To implement the stack operations with constant time complexity.
Steps:
• Use a linked list node to store each element and the minimum element at that point in the stack.
• Each node should hold the current element and the minimum value up to that element.
• The push operation should update the minimum if the current element is smaller than the current minimum.
• The pop operation should simply remove the top node from the stack.
• The top operation should return the value of the top node.
• The getMin operation should return the minimum value stored in the top node.
Goal: The stack supports constant-time operations for each function.
Steps:
• Each function should operate in O(1) time complexity.
Assumptions:
• The stack is non-empty when pop, top, and getMin are called.
Input: [[], [-2], [0], [-3], [], [], [], []]
Explanation: This series of operations initializes the MinStack and performs various operations on it. The stack changes as elements are pushed and popped, and getMin returns the current minimum element after each operation.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus