The problem. Given a valid prefix expression (operator before its operands), convert it to postfix (operator after its operands). Operands are single letters or digits; operators are + - * / ^. For example, *+AB-CD becomes AB+CD-*.
Input: "*+AB-CD" Output: "AB+CD-*"
Input: "*-A/BC-/AKL" Output: "ABC/-AK/L-*"
Input: "A" Output: "A"Neither prefix nor postfix needs brackets, so no brackets appear anywhere. Each operator just has to move from before its two operands to after them — and its operands may themselves be whole expressions.
Find an operator followed directly by two finished operands, like +AB, and replace those three items with one finished piece written in postfix: AB+. Repeat until one piece is left. (Pieces must be tracked as items, not loose characters — AB+ is one operand now, even though it contains an operator symbol.)
function prefixToPostfix(s) { const items = s.split("").map((c) => ({ text: c, op: "+-*/^".includes(c) })); while (items.length > 1) { for (let i = 0; i + 2 < items.length; i++) { // an operator followed by two finished operands is an innermost operation if (items[i].op && !items[i + 1].op && !items[i + 2].op) { const piece = items[i + 1].text + items[i + 2].text + items[i].text; items.splice(i, 3, { text: piece, op: false }); // the piece is an operand now break; // the list changed: start over } } } return items[0].text;}Time O(n²), space O(n). One rescan per operator.
Read from the left. An operand is a complete expression on its own. An operator is followed by its left operand and then its right operand, so build each one recursively and return left + right + operator.
function prefixToPostfix(s) { let i = 0; // the next character to read function build() { const c = s[i++]; if (!"+-*/^".includes(c)) return c; // an operand is complete on its own const left = build(); // the operator's first operand... const right = build(); // ...then its second return left + right + c; // the operator goes last } return build();}Time O(n), space O(n) for the recursion — and the same risk of overflowing the call stack on very deep expressions.
Exactly the stack from Prefix to Infix, with a different way of gluing. Read from the right; push operands; for an operator, pop left (it's on top, because we read backwards), pop right, and push left + right + operator.
The same scan as prefix to infix — only the glue changes.
Time O(n), space O(n), iterative. Notice that this solution never needs to know what the operators mean — no precedence, no brackets. Prefix and postfix carry the structure in their order alone.
O(n²)One rescan of the expression per operator.
O(n)The string being rewritten.
O(n)"A" stays "A"."-AB" must become "AB-", never "BA-"."+++ABCD" → "AB+C+D+"."*AA" → "AA*": operands are positions, not names.Every character is read once.
O(n)One call per operator on the stack.
O(n)Each character is pushed once; each operator pops two.
O(n)The explicit stack, which can't overflow the call stack.