1686. Nested Choice Evaluator

Medium3.5 points estimatedStackStringRecursion

A configuration language lets a value depend on switches. An expression expr is built from the conditions T and F, integer values (possibly negative and with several digits), and the symbols ? and :. A choice c?a:b evaluates to a if the condition c is T and to b if it is F; both a and b can themselves be choices, and choices group from the right, so F?1:T?-20:3 is F?1:(T?-20:3) and evaluates to -20.

A condition always directly precedes a ?; branches are integers or nested choices. Return the integer the whole expression evaluates to. Scanning from right to left with a stack of values solves it in O(n) time and O(n) space and needs no recursion, which matters for long inputs.

Example 1

Input:
expr = "T?2:3"
Output:
2
Explanation:

The condition is T, so the first branch 2 is chosen.

Example 2

Input:
expr = "F?1:T?-20:3"
Output:
-20
Explanation:

F selects the second branch T?-20:3, and T selects -20.

Example 3

Input:
expr = "T?F?5:6:7"
Output:
6
Explanation:

T selects the nested first branch F?5:6, which evaluates to 6.

Constraints

1 ≤ expr.length ≤ 104; values in [-109, 109]; expr is valid

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…