Ternary Expression Parser Problem
Description
LeetCode Problem 439.
Given a string expression representing arbitrarily nested ternary expressions, evaluate the expression, and return the result of it.
You can always assume that the given expression is valid and only contains digits, '?', ':', 'T', and 'F' where 'T' is true and 'F' is false. All the numbers in the expression are one-digit numbers (i.e., in the range [0, 9]).
The conditional expressions group right-to-left (as usual in most languages), and the result of the expression will always evaluate to either a digit, 'T' or 'F'.
Example 1:
Input: expression = "T?2:3"
Output: "2"
Explanation: If true, then result is 2; otherwise result is 3.
Example 2:
Input: expression = "F?1:T?4:5"
Output: "4"
Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as:
"(F ? 1 : (T ? 4 : 5))" --> "(F ? 1 : 4)" --> "4"
or "(F ? 1 : (T ? 4 : 5))" --> "(T ? 4 : 5)" --> "4"
Example 3:
Input: expression = "T?T?F:5:3"
Output: "F"
Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as:
"(T ? (T ? F : 5) : 3)" --> "(T ? F : 3)" --> "F"
"(T ? (T ? F : 5) : 3)" --> "(T ? F : 5)" --> "F"
Constraints:
5 <= expression.length <= 10^4expressionconsists of digits,'T','F','?', and':'.- It is guaranteed that
expressionis a valid ternary expression and that each number is a one-digit number.
Solution
Approach: Stack, Scanning from the Right
Conditionals group right to left, so the innermost expressions sit toward the right end of the string. Scanning from the right lets us evaluate every inner expression before the condition that uses it.
Keep a stack of values that are already evaluated, and walk from the last character to the first:
- a digit,
TorFthat is not a condition: push it; :: skip it; it only separates the two branches;?: the character just before it is a condition. The top of the stack is the value of its true branch, and the value below it is the value of its false branch. Pop both and push the one the condition picks. Then step over the condition character as well.
When the scan is done, the stack holds exactly one value, the result.
Why the top two values are the right ones: by the time we reach a ?, everything to its right has been reduced as far as it can go. Directly to the right of the ? there are just two complete expressions, A : B. A was pushed last, so it is on top, with B under it. In "T?T?F:5:3" the scan pushes 3, 5 and F, then turns T?F:5 into F, then T?F:3 into F.
Complexity: O(n) time and O(n) space for the stack, where n is the length of expression.
class Solution:
def parseTernary(self, expression: str) -> str:
stack = [] # values of the sub-expressions to the right, already evaluated
i = len(expression) - 1
while i >= 0:
c = expression[i]
if c == "?":
# expression[i - 1] is the condition; the top two values are its two branches.
when_true = stack.pop()
when_false = stack.pop()
stack.append(when_true if expression[i - 1] == "T" else when_false)
i -= 2 # the condition is used up too
else:
if c != ":":
stack.append(c)
i -= 1
return stack[0]