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.
- 1 <= s.length <= 5 * 10³
- Operands: a–z, A–Z, 0–9; operators: + - * / ^; brackets ( )
- ^ is right-associative, unlike the others
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.
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.
Approach
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.
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 beforeop, pop it to the output. Then pushop. - End of input: pop everything left on the stack to the output.
When a waiting operator must pop
A stacked operator top pops before op is pushed when:
tophas higher precedence thanop, or- the two have equal precedence and
opis 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-.
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.
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.
Code in Python, C++ and Java
a − b − c = (a − b) − c. Pop it.a^b^c = a^(b^c), so the new ^ must be applied before the one below. Equal precedence does not pop here; push on top.Common pitfalls
Popping on equal precedence for ^
while stack and stack[-1] != "(" and prec[stack[-1]] >= prec[ch]:
out.append(stack.pop())if top < prec[ch] or (top == prec[ch] and right):
breakOne >= 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
while stack and prec.get(stack[-1], 0) >= prec[ch]:
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
while stack[-1] != "(":
out.append(stack.pop())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
return "".join(out)
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.
Edge cases
A single operand such as a is written straight out and the stack is never used.
((a)) pushes and drops both ( with nothing between them; the output is a.
( 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.
Complexity
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.
| Notation | Operator position | Example of (a + b) * c | Needs brackets? |
|---|---|---|---|
| Infix | Between its operands | (a+b)*c | Yes |
| Postfix (RPN) | After its operands | ab+c* | No |
| Prefix (Polish) | Before its operands | *+abc | No |
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.