Evaluate a Postfix Expression
Updated
Problem statement
Evaluate a valid arithmetic expression written in postfix notation. The input is an array of tokens read from left to right. An integer token contributes a value; an operator consumes the two most recent values. The earlier value is the left operand and the later value is the right operand.
The binary operators are +, -, *, and /. Division truncates toward zero. Return the final integer value.
Function
evaluatePostfix(tokens: String[]) → intExamples
Example 1
tokens = ["2","3","+","4","*"]return = 20Add 2 and 3, then multiply the sum by 4.
Example 2
tokens = ["7","-3","/"]return = -2Seven divided by negative three truncates toward zero.
Example 3
tokens = ["5","1","2","+","4","*","+","3","-"]return = 14The expression is 5 + (1 + 2) * 4 - 3.
Constraints
1 <= tokens.length <= 10000.- Each token is a signed integer in
[-200, 200]or one of+,-,*, and/. - The tokens form a valid postfix expression, and no division has a zero divisor.
- Every intermediate result fits in a signed 32-bit integer.
More Google Onsite Interview questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Calculate a Token-List ExpressionCollege Vine · ONSITE INTERVIEW
- Basic Calculator IITypeSafe AI · OA
- Basic Calculator IISnap Inc. · PHONE SCREENSnap Inc. interview questions
- Adjacent Equal-Pair Removal GameZipRecruiter · OAZipRecruiter interview questions
- Evaluate Arithmetic with Operator PrecedenceRoblox · PHONE SCREENRoblox interview questions
- Simplify a Formula with Known and Unknown VariablesBetter.com · PHONE SCREEN
- Evaluate Parenthesized Addition and SubtractionAtlassian · PHONE SCREENAtlassian interview questions
- Smallest Value for a Linear Expression ModuloIntel · OA
- Adjacent Pair and Run RemovalWhatNot · PHONE SCREEN · ONSITE INTERVIEWWhatNot interview questions
- Single-Pass S-Expression ParserBaseten · ONSITE INTERVIEWBaseten interview questions