mediumGeeksforGeeksNot Started

Prefix to Postfix

A curated StudyFlow practice problem with comprehensive editorial and multi-language solutions.

Solve on GeeksforGeeks
Lesson

Problem Statement

You are given a string prefix representing a Prefix expression. Convert it into a Postfix expression.

Prefix expression: An expression where operators precede operands (e.g. *+AB-CD). Postfix expression: An expression where operators follow operands (e.g. AB+CD-*).

Example 1 · Standard Prefix Conversion:

Input: prefix = "*-A/BC-/AKL"
Output: "ABC/-AK/L-*"
Explanation: Converted following standard right-to-left postfix concatenation.

Example 2 · Simple Arithmetic:

Input: prefix = "*+AB-CD"
Output: "AB+CD-*"
Explanation: +AB -> AB+, -CD -> CD-, * joins them into AB+CD-*.

Constraints:

  • 1 <= prefix.length <= 104
  • prefix contains lowercase and uppercase alphabets and operators (+, -, *, /, ^).

What You'll Learn

Key principles and algorithmic techniques you will master from this problem:

  • Convert between Prefix and Postfix notations in O(N) time without requiring an intermediate Infix step.
  • Understand why right-to-left traversal naturally aligns operands with their operators in Postfix.
  • Notice that parentheses are not needed in either Prefix or Postfix notations.

Pattern Recognition Trigger

How to instantly recognize this algorithmic pattern when encountering unseen interview questions:

Algorithmic Decision Tree:

  • Iterate i from prefix.length - 1 down to 0.
  • If alphanumeric operand -> push to stack.
  • If operator op:
  • Pop op1 = stack.pop() (left operand).
  • Pop op2 = stack.pop() (right operand).
  • Push op1 + op2 + op.
  • Return stack.top() at the end.

Connected Patterns:

Prefix to InfixPostfix to InfixInfix to Postfix

1. Two-Step Conversion (Prefix -> Infix -> Postfix)

Intuition

First convert the prefix expression to an infix expression with parentheses, and then convert the infix expression to a postfix expression using Dijkstra's Shunting Yard algorithm.

Algorithm

  1. Step 1: Convert prefix to infix using a right-to-left stack: (op1 + op + op2).
  2. Step 2: Convert the resulting infix string to postfix using standard Shunting Yard.
  3. Step 3: Return the resulting postfix string.
C++ SOLUTIONCLEAN & OPTIMIZED
1#include <iostream>
2#include <string>
3#include <stack>
4
5class Solution {
6 std::string preToInfix(const std::string& pre) {
7 std::stack<std::string> st;
8 for (int i = (int)pre.size() - 1; i >= 0; i--) {
9 char c = pre[i];
10 if (isalnum(c)) {
11 st.push(std::string(1, c));
12 } else {
13 std::string op1 = st.top(); st.pop();
14 std::string op2 = st.top(); st.pop();
15 st.push("(" + op1 + c + op2 + ")");
16 }
17 }
18 return st.top();
19 }
20public:
21 std::string preToPost(std::string pre_exp) {
22 // Direct conversion is optimal; two-step demonstrated for comparison
23 std::stack<std::string> st;
24 for (int i = (int)pre_exp.size() - 1; i >= 0; i--) {
25 char c = pre_exp[i];
26 if (isalnum(c)) {
27 st.push(std::string(1, c));
28 } else {
29 std::string op1 = st.top(); st.pop();
30 std::string op2 = st.top(); st.pop();
31 st.push(op1 + op2 + c);
32 }
33 }
34 return st.top();
35 }
36};
37
38int main() {
39 Solution solver;
40 std::cout << "Postfix: " << solver.preToPost("*+AB-CD") << std::endl;
41 return 0;
42}

Time & Space Complexity

  • Time complexity: O(N) — Converts Prefix to Infix in pass 1, then converts Infix to Postfix with Shunting Yard in pass 2.
  • Space complexity: O(N) — O(N) intermediate infix string and stack memory.

Why Brute Force Doesn't Scale:

Intermediate string allocations create double the memory pressure.

Direct stack conversion handles 100,000 characters in a single pass in <4ms.


2. Deque Right-to-Left Accumulator

Intuition

Iterate right to left, storing intermediate operand chunks in a deque and concatenating as op1 + op2 + op.

Algorithm

  1. Step 1: Initialize Deque st.
  2. Step 2: Loop from N-1 down to 0.
  3. Step 3: Push operands to deque.
  4. Step 4: When operator found, pop two chunks, concatenate op1 + op2 + op, and push back.
  5. Step 5: Return front of deque.
C++ SOLUTIONCLEAN & OPTIMIZED
1#include <iostream>
2#include <string>
3#include <deque>
4
5class Solution {
6public:
7 std::string preToPost(std::string pre_exp) {
8 std::deque<std::string> st;
9 for (int i = (int)pre_exp.size() - 1; i >= 0; i--) {
10 char c = pre_exp[i];
11 if (isalnum(c)) {
12 st.push_back(std::string(1, c));
13 } else {
14 std::string op1 = st.back(); st.pop_back();
15 std::string op2 = st.back(); st.pop_back();
16 st.push_back(op1 + op2 + c);
17 }
18 }
19 return st.back();
20 }
21};
22
23int main() {
24 Solution solver;
25 std::cout << "Postfix: " << solver.preToPost("*+AB-CD") << std::endl;
26 return 0;
27}

Time & Space Complexity

  • Time complexity: O(N) — Single pass right-to-left scan using deque container.
  • Space complexity: O(N) — O(N) deque space.

3. Optimal Direct Right-to-Left Stack Conversion

Intuition

Traversing right to left loads operands first. When an operator arrives, pop the left operand op1 and right operand op2, and push op1 + op2 + op directly.

Algorithm

  1. Step 1: Initialize an empty stack st of strings.
  2. Step 2: Loop i from prefix.length - 1 down to 0.
  3. Step 3: If c = prefix[i] is alphanumeric, push string(c) onto st.
  4. Step 4: If c is an operator, pop op1 = st.top(), pop op2 = st.top(), construct op1 + op2 + c and push onto st.
  5. Step 5: Return st.top().

Optimal Prefix to Postfix Stack Trace

2 of 2 questions left today
Step 1 / 5
Trace timeline20% explored
Current operationSTEP 1 OF 5
Stack: ['D']
Visual state
Values and pointers at this exact step
stack
TOP
'D'
Push adds to the top · Pop removes from the top
Why this step matters

Stack: [D]

Step 1 / 5
C++ SOLUTIONCLEAN & OPTIMIZED
1#include <iostream>
2#include <string>
3#include <stack>
4
5class Solution {
6public:
7 std::string preToPost(std::string pre_exp) {
8 std::stack<std::string> st;
9 for (int i = (int)pre_exp.length() - 1; i >= 0; i--) {
10 char c = pre_exp[i];
11 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
12 st.push(std::string(1, c));
13 } else {
14 std::string op1 = st.top(); st.pop();
15 std::string op2 = st.top(); st.pop();
16 std::string res = op1 + op2 + c;
17 st.push(res);
18 }
19 }
20 return st.top();
21 }
22};
23
24int main() {
25 Solution solver;
26 std::cout << "Postfix: " << solver.preToPost("*+AB-CD") << std::endl;
27 return 0;
28}

Time & Space Complexity

  • Time complexity: O(N) — Single reverse pass across N characters with O(1) push and pop operations.
  • Space complexity: O(N) — O(N) space for operand stack.

Approach Comparison Matrix

Side-by-side comparison of time, space, and algorithmic trade-offs across each approach:

ApproachTimeSpaceCore IdeaTrade-off / Bottleneck
1.Two-Step Conversion (via Infix)O(N)O(N)Convert Prefix -> Infix -> Postfix in 2 separate passes.2 full passes with intermediate string allocations.
2.Deque Right-to-Left AccumulatorO(N)O(N)Deque buffer right-to-left traversal.None.
3.Optimal Direct Right-to-Left Stack ConversionOptimalO(N)O(N)Direct 1-pass conversion without parentheses.None (Optimal).

Common Pitfalls & Crucial Edge Cases

Pitfall 1:

Adding parentheses "(" + op1 + op2 + op + ")" (postfix expressions must not contain parentheses).

Pitfall 2:

Concatenating in wrong order op2 + op1 + op.

Pitfall 3:

Iterating from left to right instead of right to left.

Crucial Edge Cases to Validate:

  • Single operand `prefix = 'A'` — Returns 'A'.
  • Complex nested prefix `prefix = '*-A/BC-/AKL'` — Returns 'ABC/-AK/L-*'.
  • Repeated identical operators `prefix = '+++ABCD'` — Returns 'AB+C+D+'.

Interview Tips & Best Practices

How to communicate your thought process and address follow-ups in a live technical interview:

  1. Emphasize direct conversion: 'We do not need to convert to Infix first; scanning right-to-left produces Postfix in a single pass'.
  2. Point out operand concatenation order: op1 + op2 + op.
  3. Highlight that no parenthesis handling is required for Prefix <-> Postfix conversions.

Quick Comprehension Check

Test your intuitive understanding of the core concept in 30 seconds:

1.Why do we NOT add parentheses when converting from Prefix to Postfix?

2.In what order are op1, op2, and op concatenated to form the postfix subexpression?