Tensorum
YouTubeশেখা শুরু করুন
LeetCode 155 · Stack / Queue Design

Min Stack

LeetCode 155 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু

Push (value, min so far) pairs.

মাঝারিStackDesign
LeetCode-এ খুলুন ↗

আমি 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.