Tensorum
YouTubeसीखना शुरू करें
LeetCode 150 · Expression Evaluation

Evaluate Reverse Polish Notation

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

Operands on a stack; operator pops two.

मध्यमArrayMathStack

मैंने Evaluate Reverse Polish Notation (LeetCode 150) ऐसे हल किया — Expression Evaluation पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।

नीचे का विवरण अंग्रेज़ी में है।

Intuition

In RPN every operator applies to the two most recent values, so push numbers on a stack and, at an operator, pop two, combine, and push the result.

Approach

  1. 1

    Number → push.

  2. 2

    Operator → b = pop, a = pop, push a op b.

  3. 3

    Division truncates toward zero: int(a / b).

मैंने कैसे हल किया

Stack evaluationPythonO(n) time
class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        #store the operation with operator as key in a map
        operations = {
            "*": lambda a,b:a*b,
            "+": lambda a,b:a+b,
            "-": lambda a,b:a-b,
            "/": lambda a,b:int(a/b)
        }
        stack = []
        for token in tokens:
            if token in operations:
                b = stack.pop()
                a = stack.pop()
                operation = operations[token]
                cur_val = operation(a,b)
                stack.append(cur_val)
            else:
                stack.append(int(token))
        return stack.pop()
स्टेप-थ्रू लोड हो रहा है…

Evaluate Reverse Polish Notation — अक्सर पूछे जाने वाले प्रश्न

Evaluate Reverse Polish Notation के पीछे intuition क्या है?

In RPN every operator applies to the two most recent values, so push numbers on a stack and, at an operator, pop two, combine, and push the result.

Evaluate Reverse Polish Notation (LeetCode 150) कैसे हल करें?

1. Number → push. 2. Operator → b = pop, a = pop, push a op b. 3. Division truncates toward zero: int(a / b).

Evaluate Reverse Polish Notation की time और space complexity क्या है?

Time: O(n)। Space: O(n)। (Accepted approach: Stack evaluation।)

Evaluate Reverse Polish Notation में आम गलतियाँ क्या हैं?

Pop order matters for − and /. Python's // floors negatives; int(a / b) truncates as required.