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.