A boutique modular synthesizer lets a sound designer describe how numbered oscillator channels are blended using three panel operations written in ordinary infix notation: + (mix two channels), - (phase-cancel one channel against another), and * (ring-modulate two channels), combined with parentheses for grouping. Each single digit 0-9 in the formula names one raw channel (a leaf of the underlying operation tree).
The synth's onboard sequencer cannot evaluate the formula directly the way a human reads it. Instead it must be told the root operation first — the very last combination that produces the final signal — before it can recurse into how each side of that operation was built. In other words, you must report the formula's operation tree in root-first (preorder / prefix) order: print the operation (or channel) at the root, then the entire left subtree in the same root-first order, then the entire right subtree in the same root-first order.
The tree is built the same way a calculator would parse the formula: * binds tighter than +/-, operators of equal precedence group left to right (so 9-8-7 is (9-8)-7, not 9-(8-7)), and parentheses override precedence exactly as written.
A single line containing the patch formula: a non-empty string made only of the characters 0-9, +, -, *, (, and ).
Print the operation tree's root-first (preorder) traversal as tokens separated by single spaces: each token is either an operator (+, -, *) or a single digit. End with a newline.
+/-.0-9); there are no multi-digit numbers.Example 1
Input
1+2*3
Expected
+ 1 * 2 3
Explanation
Multiplication binds tighter than addition, so `2*3` is resolved as one subtree and the root operation is `+`, combining leaf `1` with that subtree. Root-first order visits the root `+` first, then its left child `1`, then its right subtree `* 2 3`, giving `+ 1 * 2 3`.
Example 2
Input
(1+2)*3
Expected
* + 1 2 3
Explanation
The parentheses force `1+2` to be computed as a single unit, so the root operation is `*`, combining that addition subtree with leaf `3`. Root-first order gives the root `*`, then the left subtree `+ 1 2`, then the right leaf `3`, i.e. `* + 1 2 3`.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →