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.