DSA AnimatorREVISION VIDEOS
← Back to problems
New

Evaluate Reverse Polish Notation — LeetCode 150 video explanation

Evaluate an expression written in reverse Polish notation. Each operator comes after its two operands, so there are no brackets.

Loading videos…

DSA Animator › DSA Revision › Stack › Evaluate Reverse Polish Notation

Key moments in the Evaluate Reverse Polish Notation video

0:04Problem0:13Example0:19Brute force0:28Key idea0:40Dry run0:51Code1:03Takeaway

What you will learn

Remember: operands go on the stack, operators pop two and push one. The first pop is the right operand. The video solves Evaluate Reverse Polish Notation (LeetCode 150, Medium) with the Stack pattern from the Stack topic, and you can replay every step in the interactive Evaluate Reverse Polish Notation animation.

Evaluate Reverse Polish Notation video transcript

Problem

Evaluate an expression written in reverse Polish notation. Each operator comes after its two operands, so there are no brackets.

Example

The tokens 2, 1, plus, 3, times mean 2 plus 1, then times 3. The answer is 9.

Brute force

Converting it back to normal notation with brackets is slow and complicated. The notation is designed to be evaluated with a stack.

Key idea

Read the tokens left to right. Push every number onto the stack. For an operator, pop two numbers, apply it, and push the result. Be careful with order: the first number popped is the right operand.

Dry run

Push 2. Push 1. Plus pops 1 and 2, and pushes 3. Push 3. Times pops 3 and 3, and pushes 9. One number is left: the answer is 9.

Code

In code, loop over the tokens. For an operator, pop b, then a, and push a operator b. Otherwise, parse the token as a number and push it. Return the last value, so it's O of n time and O of n space.

Takeaway

Remember: operands go on the stack, operators pop two and push one. The first pop is the right operand.

More Stack revision videos

← All 185 DSA revision videos