GeeksforGeeks Medium

Infix to Postfix Conversion

Infix to Postfix Conversion is a GFG problem (Medium). You are given an expression s in ordinary infix form, where each operator sits between its two operands, and must return the same expression in postfix form (Reverse Polish Notation), where each operator comes after its operands.

  • Operands are single letters or digits.
  • Operators are +, -, *, / and ^, and the expression may contain ( and ).
  • Precedence: ^ is highest, then * and /, then + and -.
  • Associativity: ^ groups right to left; the other four group left to right.
  • The output contains no brackets and no spaces.
Constraints
  • 1 <= s.length <= 5 * 10³
  • Operands: a–z, A–Z, 0–9; operators: + - * / ^; brackets ( )
  • ^ is right-associative, unlike the others
stackstringsparsing
Open on GeeksforGeeks ↗
02

Intuition

Postfix keeps the operands in the same order as the infix string; only the operators move. Each operator must come after its right operand, and after any tighter operator inside that operand.

So operands are written the moment they are read, while operators wait on a stack. When a new operator arrives, any waiting operator that binds at least as tightly already has both operands written, so it pops to the output. A looser one keeps waiting, because its right operand is the result of the new operator.

That one comparison against the top is the whole of infix to postfix conversion using stack, known as Dijkstra's shunting-yard algorithm. Brackets and the end of the input add two small rules.

How to spot this pattern

Reach for this pattern when the input is a flat expression with precedence or brackets and the work is to reorder or evaluate it in one pass: converting to postfix or prefix, evaluating an infix string (Basic Calculator), or building an expression tree. Operands pass straight through; operators queue on a stack and leave when something of lower or equal binding strength arrives.

03

Approach

Try it first

Before reading on, convert a-b-c and a^b^c by hand. The two look alike but give differently shaped answers. Write down the one comparison rule that produces both.

1

The algorithm for converting infix to postfix

Scan s once, left to right, with an empty operator stack and an empty output. Each character falls into one of four cases, and the input ending is a fifth:

  • Operand: append it to the output.
  • (: push it.
  • ): pop operators to the output until the top is (, then pop the ( and throw both brackets away.
  • Operator op: while the top is an operator that must apply before op, pop it to the output. Then push op.
  • End of input: pop everything left on the stack to the output.
2

When a waiting operator must pop

A stacked operator top pops before op is pushed when:

  • top has higher precedence than op, or
  • the two have equal precedence and op is left-associative.

For the right-associative ^, equal precedence does not pop: in a^b^c the second ^ must apply first, so it is pushed above the first one and both come out at the end, giving abc^^. With -, the earlier one pops, giving ab-c-.

3

Brackets as barriers

( is pushed with no precedence, and the popping loop stops at it. Operators inside a group can therefore never pop operators that wait outside it. When ) arrives the group is finished, so every operator still inside it has both operands, and they all pop. Neither bracket is ever written to the output: the order they forced is all that remains of them.

4

Why the order comes out right

An operator is written only when its right operand is complete. That happens at one of three moments: an operator that binds no tighter arrives, the enclosing ) arrives, or the input ends. Operators leave the stack top first, so the innermost operation is written first, which is exactly the evaluation order a postfix reader needs.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def infixToPostfix(self, s):
▶3 prec = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}
▶4 out, stack = [], []
▶5 for ch in s:
▶6 if ch.isalnum():
▶7 out.append(ch)
▶8 elif ch == "(":
▶9 stack.append(ch)
▶10 elif ch == ")":
▶11 while stack[-1] != "(":
▶12 out.append(stack.pop())
▶13 stack.pop()
▶14 else:
▶15 right = ch == "^"
▶16 while stack and stack[-1] != "(":
▶17 top = prec[stack[-1]]
▶18 if top < prec[ch] or (top == prec[ch] and right):
▶19 break
▶20 out.append(stack.pop())
▶21 stack.append(ch)
▶22 while stack:
▶23 out.append(stack.pop())
▶24 return "".join(out)
infix inputa+b*c-doperator stackpostfix outputoperands go straight out; operators wait
ranks+ − 1, * / 2, ^ 3
length7
Idea. An operand's place in postfix is known the moment it is read. An operator's is not: it has to come after its right operand, and after any tighter operator that follows. So operators wait on a stack until something proves they are safe to write.
infix inputa+b*c-doperator stackpostfix outputa'a' is an operand → write it
s[0]'a'operand
stack[]bottom → top
outputa
a is an operand. Postfix keeps operands in their original order, so it goes straight to the output; only operators get reordered.
infix inputa+b*c-doperator stack+rank 1toppostfix outputapush '+' and let it wait
s[1]'+'rank 1
stack[+]bottom → top
outputa
The stack is empty, so nothing waits ahead of +. Push it; its right operand has not been read yet.
infix inputa+b*c-doperator stack+rank 1toppostfix outputab'b' is an operand → write it
s[2]'b'operand
stack[+]bottom → top
outputab
b is written at once, even though + is still waiting: operands never wait. + stays: the next operator may bind tighter and take b as its own left operand, in which case it must be written first.
infix inputa+b*c-doperator stack+rank 1*rank 2toptop vs incoming+rank 1<*rank 2binds looser → staypostfix outputabpush '*' and let it wait
s[3]'*'rank 2
stack[+ *]bottom → top
outputab
+ binds looser than *, so it has to wait for the result of *. Nothing pops; push * on top of it.
infix inputa+b*c-doperator stack+rank 1*rank 2toppostfix outputabc'c' is an operand → write it
s[4]'c'operand
stack[+ *]bottom → top
outputabc
c is written at once, even though * is still waiting: operands never wait. * stays: the next operator may bind tighter and take c as its own left operand, in which case it must be written first.
infix inputa+b*c-doperator stack+rank 1top*outtop vs incoming*rank 2>-rank 1binds tighter → poppostfix outputabc*pop '*' to the output
top'*'rank 2
incoming'-'rank 1
stack[+]bottom → top
outputabc*
* binds tighter than -, so it must be applied first. Its right operand is already in the output, so pop it now.
infix inputa+b*c-doperator stack+outtop vs incoming+rank 1=-rank 1equal, groups left → poppostfix outputabc*+pop '+' to the output
top'+'rank 1
incoming'-'rank 1
stack[]bottom → top
outputabc*+
Same precedence, and - is left-associative: the earlier + is applied first, like a − b − c = (a − b) − c. Pop it.
infix inputa+b*c-doperator stack-rank 1toppostfix outputabc*+push '-' and let it wait
s[5]'-'rank 1
stack[-]bottom → top
outputabc*+
The stack is empty, so nothing waits ahead of -. Push it; its right operand has not been read yet.
infix inputa+b*c-doperator stack-rank 1toppostfix outputabc*+d'd' is an operand → write it
s[6]'d'operand
stack[-]bottom → top
outputabc*+d
d is written at once, even though - is still waiting: operands never wait. - stays: the next operator may bind tighter and take d as its own left operand, in which case it must be written first.
infix inputa+b*c-doperator stack-outpostfix outputabc*+d-input done → pop what is left
popped'-'
stack[]bottom → top
outputabc*+d-
The input is used up, so both operands of - are already written. Pop it. Top-first order is right: the operator pushed last is the innermost and applies first.
infix inputa+b*c-doperator stackpostfix outputabc*+d-answer: abc*+d-
result"abc*+d-"
Done. Read left to right, each operator now acts on the two values just before it, so no brackets or precedence rules are needed to evaluate abc*+d-.
05

Common pitfalls

Popping on equal precedence for ^

✗ Wrong
while stack and stack[-1] != "(" and prec[stack[-1]] >= prec[ch]:
    out.append(stack.pop())
✓ Right
if top < prec[ch] or (top == prec[ch] and right):
    break

One >= for every operator makes ^ left-associative: a^b^c becomes ab^c^, which means (a^b)^c. Exponentiation groups from the right, so the answer must be abc^^.

Letting the pop loop cross a bracket

✗ Wrong
while stack and prec.get(stack[-1], 0) >= prec[ch]:
✓ Right
while stack and stack[-1] != "(":

Without the ( check, an operator inside a group can pop operators that are waiting outside it, and the bracket itself can end up compared or written. The ( must stop the loop.

Forgetting to discard the opening bracket

✗ Wrong
while stack[-1] != "(":
    out.append(stack.pop())
✓ Right
while stack[-1] != "(":
    out.append(stack.pop())
stack.pop()

The ( stays on the stack after its group closes and is later flushed into the output, so (a+b)*c comes out as ab+c*(.

Not flushing the stack at the end

✗ Wrong
return "".join(out)
✓ Right
while stack:
    out.append(stack.pop())
return "".join(out)

Any expression ending in an operand leaves its last operators waiting. a+b*c would return just abc.

06

Edge cases

Expression with no operators

A single operand such as a is written straight out and the stack is never used.

Redundant brackets

((a)) pushes and drops both ( with nothing between them; the output is a.

Very deep nesting, e.g. 2,500 ( then a then 2,500 )

The stack grows to about n/2 entries. An explicit stack has no depth limit, while a recursive parser in Python would pass its default limit of 1,000 calls.

07

Complexity

Time
O(n)
Space
O(n)
Every operator and bracket is pushed once and popped once, and every operand is written once. The stack and the output each hold at most n characters.
08

Infix, postfix and prefix

The three notations write the same expression with the operator in a different place. Only infix needs precedence rules and brackets to be read correctly.

NotationOperator positionExample of (a + b) * cNeeds brackets?
InfixBetween its operands(a+b)*cYes
Postfix (RPN)After its operandsab+c*No
Prefix (Polish)Before its operands*+abcNo
09

Infix to Postfix Conversion FAQ

Why is a stack the right data structure for this?

The operator that must be written next is always the most recently read one still waiting, because nesting and precedence both resolve inside-out. Last in, first out is exactly a stack.

How do you evaluate the postfix expression afterwards?

Scan it with a stack of values: push each operand, and on each operator pop two values, apply it (second popped on the left), and push the result. The single value left is the answer. For example, ab+c* with a=2, b=3, c=4 pushes 2 and 3, adds them to 5, pushes 4, and multiplies to 20. This is Evaluate Reverse Polish Notation (LeetCode 150).

How is infix to prefix conversion different?

Reverse the infix string and swap ( with ), run the same postfix routine with the equal-precedence rule flipped (+ - * / no longer pop an equal operator, ^ does), then reverse the result.