← DiffPush

Prefix to Infix Conversion

Standard Bar Stack and Queues · Infix, Postfix, and Prefix O(n) · O(n)

The Dispatch Ledger Decoder

A logistics hub receives machine-generated dispatch codes written operator-first (`- A B` meaning A minus B) and human auditors need them back in ordinary form. Because an operator-first code always names the operation before listing its two operands, the decoder scans backwards, keeping partially built operand groups on a shelf, and joins the top two groups whenever an operator appears.

Input: A string expression in valid prefix form with single alphanumeric operands.

Output: Return the fully parenthesized infix expression as a string.

Constraints

Examples

Example 1

Input: {"expression":"*-A/BC-/AKL"}
Output: "((A-(B/C))*((A/K)-L))"
Scanning backwards, each operator wraps the two groups already on the shelf, rebuilding the parenthesized tree.

Example 2

Input: {"expression":"+AB"}
Output: "(A+B)"
The minimal case: one operator, two operands, one pair of parentheses.

Solve this in your browser →

Also on LeetCode ↗