Introduction
Prefix to Infix conversion means converting a mathematical expression from prefix notation into infix notation.
Prefix notation:
+ABInfix notation:
A+BIn prefix notation:
- operators are written before operands
In infix notation:
- operators are written between operands
Example:
Input: *+ABCOutput: ((A+B)*C)Explanation:
- +AB becomes (A+B)
- then multiplied with C
Constraints
Expression contains:Operands:
A-Z, a-z, 0-9
Operators:
+, -, *, /, ^
Approach 1 : Brute Force (Manual Expression Building)
Explanations:
Explanation:
The idea is to manually combine operators and operands.
Steps:
- Traverse prefix expression.
- Detect operators.
- Combine operands manually.
- Build infix expression.
This approach becomes difficult for:
- nested expressions
- large expressions
- precedence handling
So stack-based conversion is preferred.
Dry Run
Input:*+ABC
Traversal from right:
C → operand
B → operand
A → operand
+ → combine:
(A+B)
* → combine:
((A+B)*C)
Final Output:
((A+B)*C)
Practice :
Complexity Analysis :
Time Complexity:- O(n)Explanation :
Expression is traversed once.
Space Complexity:- O(n)
Explanation :
Stack stores intermediate expressions.
Approach 2 : Optimal Solution(Using Stack)
Explanations:
Explanation:
This is the most optimized and interview-preferred solution.
The idea is:
- traverse expression from right to left
- push operands into stack
- when operator appears:
- pop two operands
- combine expression
- push back into stack
At the end:
- stack contains final infix expression
This efficiently converts prefix expressions into infix expressions.
Dry Run
Input:*+ABC
Step 1:
Push C
Stack:
[C]
Step 2:
Push B
Stack:
[C, B]
Step 3:
Push A
Stack:
[C, B, A]
Step 4:
+ operator
(A+B)
Stack:
[C, (A+B)]
Step 5:
* operator
((A+B)*C)
Final Output:
((A+B)*C)
Practice :