DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 150. Evaluate Reverse Polish Notation

Evaluating Reverse Polish Notation (RPN) – Approach & Learnings

Approach

  • Use a stack to process the tokens in a single pass.
  • If the token is a number, push it onto the stack.
  • If the token is an operator (+, -, *, /):
    • Pop two elements from the stack (a = pop(), b = pop()).
    • Apply the operator in the correct order (b op a).
    • Push the result back onto the stack.
  • The final value left in the stack is the result.

Time Complexity

  • O(N), where N is the number of tokens.
    • Each token is processed exactly once.
    • Stack operations (push/pop) take O(1) time each.

Key Learnings

  1. Type Handling is Critical

    • Ensure all numbers are Number, not strings (Number(token)).
    • Explicitly return Number(myStack.pop()) to avoid type errors.
  2. Correct Order of Operations

    • Since the stack is LIFO, pop order matters:
     let a = stack.pop();
     let b = stack.pop();
    
 - For subtraction and division, **order is crucial**: `b - a`, `b / a`.  
Enter fullscreen mode Exit fullscreen mode
  1. Handling Integer Division

    • JS division (/) results in float, but integer division is expected.
    • Use Math.trunc(b / a) to truncate towards zero.
  2. Cleaner Operator Handling

    • Use a function dictionary for better readability:
     let operations = {
         "+": (a, b) => a + b,
         "-": (a, b) => b - a,
         "*": (a, b) => a * b,
         "/": (a, b) => Math.trunc(b / a)
     };
    

Code Implementation

var evalRPN = function(tokens) {
    let stack = [];

    let operations = {
        "+": (a, b) => b + a,
        "-": (a, b) => b - a,
        "*": (a, b) => b * a,
        "/": (a, b) => Math.trunc(b / a)  // Truncate towards zero
    };

    for (let token of tokens) {
        if (operations[token]) {
            let a = stack.pop();
            let b = stack.pop();
            stack.push(operations[token](Number(a), Number(b)));
        } else {
            stack.push(Number(token));
        }
    }
    return Number(stack.pop());  // Ensure correct return type
};
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay