imashutosh51

155. Min Stack

Jan 24th, 2026
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.78 KB | None | 0 0
  1. '''
  2. • We need a way to always know the minimum so far without scanning the whole stack, since that would be O(n).
  3.  
  4. • While pushing, store not only the value but also the minimum up to that point, so every stack level “remembers” the smallest value below it.
  5.  
  6. • Then pop, top, and getMin become simple lookups from the top element, all in O(1) time.
  7. '''
  8.  
  9. class MinStack:
  10.     def __init__(self):
  11.         self.st = []
  12.  
  13.     def push(self, val: int) -> None:
  14.         if not self.st:
  15.             self.st.append((val, val))
  16.         else:
  17.             self.st.append((val, min(val, self.st[-1][1])))
  18.  
  19.     def pop(self) -> None:
  20.         self.st.pop()
  21.  
  22.     def top(self) -> int:
  23.         return self.st[-1][0]
  24.  
  25.     def getMin(self) -> int:
  26.         return self.st[-1][1]
  27.  
Advertisement
Add Comment
Please, Sign In to add comment