712246. Prefix to Postfix Conversion
Medium
Prefix to Postfix Conversion
Slug: prefix-to-postfix-conversion Difficulty: Medium Id: 712246
Summary
The problem is about converting a given mathematical expression from prefix notation to postfix notation. The input expression is a string consisting of operands (single-character letters) and operators (+, -, *, /). The goal is to convert the expression into its equivalent postfix form.
Detailed Explanation
To solve this problem, we can use a stack-based approach. We iterate through the input expression from left to right, processing each token (operand or operator).
Token Processing
- Operands: When an operand is encountered, simply push it onto the stack.
- Operators: When an operator is encountered:
- If the stack is empty, push the operator onto the stack.
- Otherwise, pop operators from the stack and append them to the output string until an empty stack or a left parenthesis '(' is encountered. Then, push the current operator onto the stack.
Postfix Conversion
- Once all tokens have been processed:
- Pop any remaining operators from the stack and append them to the output string.
- The resulting string is the postfix conversion of the input expression.
Time Complexity: O(n), where n is the length of the input expression. Space Complexity: O(n), as we need to store the intermediate results on the stack.
Optimized Solutions
Java
public String prefixToPostfix(String expression) {
Stack<Character> stack = new Stack<>();
StringBuilder output = new StringBuilder();
for (char c : expression.toCharArray()) {
if (Character.isLetter(c)) {
stack.push(c);
} else {
while (!stack.isEmpty() && stack.peek() != '(') {
output.append(stack.pop());
}
stack.push(c);
}
}
while (!stack.isEmpty()) {
output.append(stack.pop());
}
return output.toString();
}