Tensorum
YouTubeसीखना शुरू करें
LeetCode 155 · Stack / Queue Design

Min Stack

LeetCode 155 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Push (value, min so far) pairs.

मध्यमStackDesign

मैंने 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. 1

    push: pair the value with min(value, previous min).

  2. 2

    pop: pop the pair.

  3. 3

    top: first element of the top pair.

  4. 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.