Skip to content

ORIGINAL CODING QUESTION

Evaluate a bracketed scoring formula

A grading rubric stores an infix scoring formula as integer tokens. Tokens 0 to 100 are numbers; 101 means plus, 102 minus, 103 times, 104 an opening bracket and 105 a closing bracket. Multiplication binds tighter than plus and minus, operators of equal strength apply from left to right, and brackets group as usual. There is no unary minus. Return the value of the formula.

Open practice workspace

Original exercise · hard. Editorial role relevance does not imply a company has asked this question.

Input and output

n, then n tokens forming a valid formula. Print its value.

Constraints

1 ≤ n ≤ 199; the formula is valid; every intermediate and final value has absolute value at most 1,000,000,000.

Example 1

Input

5
2 101 3 103 4

Output

14

Times first: 2 + (3 * 4) = 14.

Example 2

Input

7
104 2 101 3 105 103 4

Output

20

The bracket forces (2 + 3) * 4 = 20.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

Left-to-right evaluation ignores precedence: 2 + 3 * 4 must be 14, not 20.

Hint 2

Keep one stack of numbers and one of pending operators; before pushing an operator, apply stacked operators of equal or higher strength.

Hint 3

An opening bracket is pushed as a barrier; a closing bracket applies operators down to that barrier and removes it. Apply whatever remains at the end.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →