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.