Skip to the code
cf.
+25 XP

#282 Convert a Formula to Postfix

medium

Before storing a formula, a spreadsheet converts it from the usual infix form (operators between operands) into postfix form (each operator after its operands), which is easy to evaluate later.

Write toPostfix(tokens) that takes the infix tokens (non-negative integers as strings, +, -, *, /, (, )) and returns the postfix tokens. * and / bind more tightly than + and -, operators of equal precedence group left to right, and parentheses don't appear in the output. For example 3 + 4 * 2 becomes 3 4 2 * +.

Example 1

Input: tokens = ["3","+","4","*","2"]
Output: ["3","4","2","*","+"]

* binds first, so it comes right after its operands 4 2.

Example 2

Input: tokens = ["(","3","+","4",")","*","2"]
Output: ["3","4","+","2","*"]

The parentheses make + happen first.

Constraints

  • 1 <= tokens.length <= 10^4
  • The formula is valid.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).