← L&T Mindtree bank

L&T Mindtree · Question 23 · Stacks

Evaluate Reverse Polish Notation

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

Problem

You are given an array of strings representing arithmetic expression in Reverse Polish Notation. Evaluate it.

Approach

Push operands; on an operator combine the top two and push back, truncating division toward zero.

Time O(n)Space O(n)

How it works

  1. 1Numbers push onto the stack.
  2. 2Operators pop two operands and push the result.

Sample input / output

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

Constraints

Valid RPN; 32-bit results.

Solution — read it, then walk it

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

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