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.