← Uber bank

Uber · Question 28 · Stacks

Evaluate Reverse Polish Notation

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

Problem

Evaluate the value of an arithmetic expression in Reverse Polish Notation (postfix notation). Supports +, -, *, /.

Approach

Use a stack: push operands; on an operator pop two operands, evaluate, push back. Division truncates toward zero.

Time O(n)Space O(n)

How it works

  1. 1Push every number onto the stack.
  2. 2On an operator, pop two operands and push the result.
  3. 3Integer division truncates toward zero.

Sample input / output

Input:
5
2 1 + 3 *
Output:
9

Constraints

1 <= tokens.length <= 10^4; valid RPN; intermediate results fit 32-bit.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 1Branches 7Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesnoyesno↻ repeatyesnoSTARTliststack = []ops = {'+', '-', '*', '/'}for t in tokensif t not in opsstack.append(int(t))ELSEb = stack.pop()a = stack.pop()if t == '+'stack.append(a + b)elif t == '-'stack.append(a - b)elif t == '*'stack.append(a * b)ELSEstack.append(int(a / b))RETURN stack[-1]DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it))tokens = [next(it) for _ inrange(n)]print(evalRPN(tokens))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/28

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