283 words
1 minutes
LeetCode155:Min Stack(Medium)-OOD
2025-04-19

LeetCode155. Min Stack(OOD)#

πŸ“Œ Problem Description#

Design a stack (MinStack) that supports the following operations:

  • push(val): Push an element onto the stack.
  • pop(): Remove the top element.
  • top(): Get the top element.
  • getMin(): Retrieve the minimum element in the stack in O(1) time.

βœ… Optimal Approach: Auxiliary Stack (Min Stack)#

Use two stacks:

  • stack: The regular value stack.
  • min_stack: Tracks the minimum value at each stage.

Example Workflow:#

push(3)  β†’ stack=[3],     min_stack=[3]
push(2)  β†’ stack=[3,2],   min_stack=[3,2]
push(1)  β†’ stack=[3,2,1], min_stack=[3,2,1]
pop()    β†’ stack=[3,2],   min_stack=[3,2]
getMin() β†’ return 2

Python Implementation:#

class MinStack:

    def __init__(self):
        self.stack = []
        self.min_stack = []

    def push(self, val: int) -> None:
        self.stack.append(val)
        if not self.min_stack or val <= self.min_stack[-1]:
            self.min_stack.append(val)

    def pop(self) -> None:
        val = self.stack.pop()
        if val == self.min_stack[-1]:
            self.min_stack.pop()

    def top(self) -> int:
        return self.stack[-1]

    def getMin(self) -> int:
        return self.min_stack[-1]

🧩 Alternative Approaches (Keeping O(1) getMin)#

MethodSpace ComplexityNotes
Auxiliary stack (above)O(n)Most recommended
Store (val, min) tuplesO(n)Compact, no second stack needed
Difference trick (val - min)O(n)Space-saving but complex logic
Min-heap (priority queue)❌Does not satisfy O(1) requirement

🧠 OOD (Object-Oriented Design) Recap#

Basic Class and Object Structure:#

class MyClass:
    def __init__(self):
        self.data = []

    def method(self):
        # self refers to the current instance
        self.data.append(1)

Understanding self:#

  • self represents the current object
  • Variables like self.xxx in __init__() are instance attributes
  • Always use self.xxx to access or modify instance data within class methods

Method Calling Process:#

obj = MyClass()     # Creates an object, self refers to obj
obj.method()        # Equivalent to MyClass.method(obj)

❗ Common Mistakes#

TypeDescriptionExample
Using remove() to delete minRemoves the first match, not necessarily the topself.min_stack.remove(val) ❌
Using > instead of >=Misses duplicate minsShould use val <= min_stack[-1]
Verbose use of len() + indexingUnnecessary complexityUse [-1] and .pop() instead

βœ… Summary#

  • The key is to support O(1) retrieval of the current minimum value
  • The best approach is to maintain an auxiliary stack for minimums
  • Mastering self and instance state is crucial for solid OOD
LeetCode155:Min Stack(Medium)-OOD
https://nanshanvv.github.io/shuchangwen-webpage/posts/leetcode/155/
Author
Shuchang Wen
Published at
2025-04-19