Min Stack
LeetCode 155 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Push (value, min so far) pairs.
నేను Min Stack (LeetCode 155) ను ఇలా పరిష్కరించాను — Stack / Queue Design ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Store, with every pushed value, the minimum of the stack at that moment. The current minimum is then always on top, and popping automatically restores the previous minimum.
Approach
- 1
push: pair the value with min(value, previous min).
- 2
pop: pop the pair.
- 3
top: first element of the top pair.
- 4
getMin: second element of the top pair.
నేను ఎలా పరిష్కరించాను
Value + running-min pairsPythonO(1) per op
class MinStack:
def __init__(self):
self.items = []
def push(self, val: int) -> None:
if not self.items:
self.items.append((val,val))
else:
min_val = self.items[-1][1]
self.items.append((val,min(min_val,val)))
def pop(self) -> None:
self.items.pop()
def top(self) -> int:
if self.items:
item = self.items[-1]
return item[0]
return None
def getMin(self) -> int:
return self.items[-1][1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()Min Stack — తరచూ అడిగే ప్రశ్నలు
Min Stack వెనుక ఉన్న intuition ఏమిటి?
Store, with every pushed value, the minimum of the stack at that moment. The current minimum is then always on top, and popping automatically restores the previous minimum.
Min Stack (LeetCode 155) ను ఎలా పరిష్కరించాలి?
1. push: pair the value with min(value, previous min). 2. pop: pop the pair. 3. top: first element of the top pair. 4. getMin: second element of the top pair.
Min Stack యొక్క time, space complexity ఎంత?
Time: O(1) per operation. Space: O(n). (Accepted approach: Value + running-min pairs.)
Min Stack లో సాధారణ పొరపాట్లు ఏమిటి?
A single 'current min' variable can't recover the old min after a pop.