Leetcode 150: Evaluate Reverse Polish Notation

grid47
grid47
Exploring patterns and algorithms
Oct 23, 2024 6 min read

A glowing stack of numbers, gently unfolding and calculating the final result step-by-step.
Solution to LeetCode 150: Evaluate Reverse Polish Notation Problem

You are given an array of strings tokens that represents an arithmetic expression in Reverse Polish Notation (RPN). Your task is to evaluate the expression and return the result as an integer.
Problem
Approach
Steps
Complexity
Input: The input consists of an array of strings, where each string is either an operand (integer) or an operator (+, -, *, /).
Example: tokens = ["3", "4", "-", "5", "*"]
Constraints:
• 1 <= tokens.length <= 10^4
• tokens[i] is either an operator (+, -, *, /) or an integer between [-200, 200].
Output: The output should be an integer representing the result of evaluating the RPN expression.
Example: Result = -35
Constraints:
• The answer can be represented as a 32-bit integer.
Goal: Evaluate the Reverse Polish Notation expression by using a stack to process operands and operators.
Steps:
• Initialize an empty stack.
• Iterate through the tokens array:
• - If the token is an integer, push it onto the stack.
• - If the token is an operator (+, -, *, /), pop the top two elements from the stack, apply the operator, and push the result back onto the stack.
• At the end of the iteration, the stack will contain only one element, which is the result of the expression.
Goal: The expression will always be valid and can be evaluated.
Steps:
• 1 <= tokens.length <= 10^4
• tokens[i] is an operator (+, -, *, /) or an integer between [-200, 200].
Assumptions:
• The expression will always be valid and contain no division by zero.
Input: tokens = ["3", "4", "-", "5", "*"]
Explanation: First, 3 - 4 = -1, then -1 * 5 = -35. So the result is -35.

Input: tokens = ["2", "3", "*", "4", "+"]
Explanation: First, 2 * 3 = 6, then 6 + 4 = 10. So the result is 10.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus