← PayPal bank

PayPal · Question 46 · Stacks

Evaluate Reverse Polish Notation

StacksJavacode⏱ O(n)💾 O(n)
Product-based

Problem

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Approach

Use a stack to evaluate operands and operators.

Time O(n)Space O(n)

How it works

  1. 1Numbers push onto the stack.
  2. 2Operators consume two operands and push the result (truncating division).

Sample input / output

Input:
tokens = ["4", "13", "5", "/", "+"]
Output:
6

Constraints

Valid RPN; division truncates toward zero.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 1Branches 4Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesnoyesno↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static intevalRPN(String[] tokens)Stack<Integer> stack = newStack<>()for (String token :tokens)if ("+".equals(token))DEFINE b = stack.pop()DEFINE a = stack.pop()stack.push(a + b)else if("-".equals(token)) {DEFINE b = stack.pop()DEFINE a = stack.pop()stack.push(a - b)else if("*".equals(token)) {DEFINE b = stack.pop()DEFINE a = stack.pop()stack.push(a * b)else if("/".equals(token)) {DEFINE b = stack.pop()DEFINE a = stack.pop()stack.push(a / b)} elseRETURN stack.pop()DEFINE static voidmain(String[] args)System.out.println(evalRPN(newString[]{"4", "13", "5","/", "+"}))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/26

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits