Postfix to Prefix Conversion in Java
Postfix to Prefix Conversion
Postfix to Prefix Conversion in Java is a common stack based problem that helps you understand how expression parsing works.
If you are learning stacks, compilers basics, or preparing for coding interviews, this topic shows up a lot because it is simple in idea but easy to mess up in implementation.
In this article, you will learn what postfix and prefix mean, why conversion is needed, the most reliable methods, step by step algorithms, edge cases (like invalid expressions), and a complete runnable Java program with example input/output.
What is Postfix to Prefix Conversion means?
An expression like A + B can be written in different notations:
- Infix: A + B (operators between operands)
- Postfix (Reverse Polish Notation): AB+ (operator after operands)
- Prefix (Polish Notation): +AB (operator before operands)
Postfix to Prefix conversion means: Given a postfix expression, build an equivalent prefix expression.
2. Expression trees (building ASTs)
3. Stack based evaluation engines
4. Interview questions to test stack fundamentals
Algorithm for Postfix to Prefix Conversion in Java
- Create an empty stack of strings.
- For each character/token ch in the postfix expression:
- If ch is an operand:
- Push String.valueOf(ch) onto the stack.
- Else if ch is an operator:
If stack has fewer than 2 items, expression is invalid (underflow).
Pop right
Pop left
Combine: prefix = ch + left + right
Push prefix
- Else ignore whitespace (or treat as invalid based on your input rules).
- If ch is an operand:
- After scanning:
- If stack size is not exactly 1, expression is invalid (extra operands/operators).
- Single item on stack is the prefix expression.
Learn DSA
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Java Code for Postfix to Prefix Conversion
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;
public class PostfixToPrefixConversion {
// Checks if a character is an operator we support
private static boolean isOperator(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^';
}
// Checks if a character is an operand (letter or digit)
// For beginner-friendly version: single-letter variables or single-digit numbers.
private static boolean isOperand(char ch) {
return Character.isLetterOrDigit(ch);
}
/**
* Converts a postfix expression to prefix expression.
* Assumptions:
* - Operands are single letters/digits (A, b, 7, etc.)
* - Operators are one of: +, -, *, /, ^
* - Spaces are allowed and ignored
*
* @param postfix input postfix string
* @return prefix expression string
* @throws IllegalArgumentException if postfix is invalid
*/
public static String postfixToPrefix(String postfix) {
if (postfix == null) {
throw new IllegalArgumentException("Input is null.");
}
String trimmed = postfix.trim();
if (trimmed.isEmpty()) {
throw new IllegalArgumentException("Input is empty.");
}
Deque stack = new ArrayDeque<>();
for (int i = 0; i < postfix.length(); i++) {
char ch = postfix.charAt(i);
// Ignore whitespace
if (Character.isWhitespace(ch)) {
continue;
}
if (isOperand(ch)) {
stack.push(String.valueOf(ch));
} else if (isOperator(ch)) {
// Underflow check: need two operands
if (stack.size() < 2) {
throw new IllegalArgumentException(
"Invalid postfix expression: not enough operands for operator '" + ch + "'.");
}
String right = stack.pop();
String left = stack.pop();
// Build prefix: operator + left + right
String combined = ch + left + right;
stack.push(combined);
} else {
// Invalid character based on our rules
throw new IllegalArgumentException(
"Invalid character '" + ch + "' found in expression.");
}
}
// After processing, exactly one result should remain
if (stack.size() != 1) {
throw new IllegalArgumentException(
"Invalid postfix expression: leftover operands/operators (stack size = " + stack.size() + ").");
}
return stack.pop();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter postfix expression (example: AB+C*):");
String postfix = sc.nextLine();
try {
String prefix = postfixToPrefix(postfix);
System.out.println("Prefix expression:");
System.out.println(prefix);
// Complexity note for this approach:
// Time: O(n), Space: O(n)
System.out.println("\nComplexity:");
System.out.println("Time Complexity: O(n)");
System.out.println("Space Complexity: O(n)");
} catch (IllegalArgumentException ex) {
System.out.println("Error: " + ex.getMessage());
} finally {
sc.close();
}
}
}
Input:
AB+C*
Output:
*+ABC
Explanation:
AB+ becomes +AB then (+AB)C* becomes *+ABC
Space Complexity: O(n) (stack can hold up to n operands/partial expressions)
Conclusion:
- Always remember: for an operator, you pop right first, then left.
- Validate input. Interviewers often test what happens with AB++ or A+.
- If the problem statement includes multi character operands (like 12, var1), you must tokenize by spaces (Ex. 12 3 +) and use a stack of strings for tokens.
The same algorithm still works, only token parsing changes.
Frequently Asked Questions
Answer:
It is the process of converting an expression from postfix form (operator after operands) to prefix form (operator before operands) using a stack-based approach.
Answer:
Scan the postfix expression left to right. Push operands. When you see an operator, pop right and left operands, combine as operator + left + right, then push back.
Answer:
For the standard stack method, the time complexity is O(n) and the space complexity is O(n).
Answer:
Because postfix places the operator after both operands. When using a stack, the most recent operand belongs to the right side of the operator.
Answer:
During conversion, if an operator appears when the stack has fewer than two operands, it is invalid. After processing, if the stack size is not exactly one, it is also invalid.
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Login/Signup to comment