Evaluate a postfix expression
Evaluate a space-separated postfix expression containing integers and the +, -, *, and / operators.
Course progress
Problem 88 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
expression = "2 1 + 3 *"
Expected output
9
What is happening?
First compute 2 + 1 = 3, then multiply that result by the final 3 to get 9.
Solution strategy
Build the right mental model
Push operands on a stack. For an operator, pop the right operand and then the left operand, calculate, and push the result.
Core concepts
stack · expression parsing
Complexity
Time O(n), space O(n).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for evaluate-postfix-expression
using System;
using System.Collections.Generic;
class Program
{
static int Evaluate(string expression)
{
var values = new Stack<int>();
foreach (string token in expression.Split(' '))
{
int number;
if (int.TryParse(token, out number)) { values.Push(number); continue; }
int right = values.Pop();
int left = values.Pop();
if (token == "+") values.Push(left + right);
else if (token == "-") values.Push(left - right);
else if (token == "*") values.Push(left * right);
else if (token == "/") values.Push(left / right);
else throw new ArgumentException("Unknown operator.");
}
if (values.Count != 1) throw new ArgumentException("Invalid expression.");
return values.Pop();
}
static void Main()
{
Console.WriteLine(Evaluate("2 1 + 3 *"));
}
}Knowledge check
Questions students often ask
What is the main idea behind evaluate a postfix expression?
Push operands on a stack. For an operator, pop the right operand and then the left operand, calculate, and push the result.
What is the time and space complexity of this solution?
Time O(n), space O(n).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.