1685. Postfix Translator

Medium3.5 points estimatedStackString

A calculator back-end needs expressions in postfix (reverse Polish) form. expr is a valid infix expression made of non-negative integers, single lowercase letters used as variables, the binary operators + - * / ^ and parentheses. Spaces may appear between tokens, and there are no unary operators.

The operator ^ binds tightest and is right-associative; * and / bind tighter than + and -; all of + - * / are left-associative. Convert the expression with the shunting-yard algorithm and return the postfix tokens in order as a string[]: each integer (all of its digits together), each variable and each operator is one token, and parentheses never appear in the output. The algorithm runs in O(n) time with an operator stack of size O(n).

Example 1

Input:
expr = "a+b*c"
Output:
["a","b","c","*","+"]
Explanation:

Multiplication binds tighter than addition, so the product is output before the sum: a b c * +.

Example 2

Input:
expr = "(1+2)*3"
Output:
["1","2","+","3","*"]
Explanation:

The parentheses force 1 + 2 first, then the multiplication by 3.

Example 3

Input:
expr = "2^3^2"
Output:
["2","3","2","^","^"]
Explanation:

The operator ^ is right-associative, so 3^2 is grouped first: 2 3 2 ^ ^.

Constraints

1 ≤ expr.length ≤ 1000; expr is valid; spaces may separate tokens

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…