Ternary Expression Parser - Problem
Ternary Expression Parser is a fascinating string parsing problem that simulates how programming languages evaluate conditional expressions.
Given a string containing nested ternary expressions (like
• T and F for boolean values (true/false)
• ? and : for ternary operators
• Single digits (0-9) as values
The ternary operator works as:
Just like in most programming languages, these expressions are right-associative, meaning they evaluate from right to left. For example,
Goal: Parse and evaluate the nested ternary expression to return a single character result.
Given a string containing nested ternary expressions (like
"T?2:F?1:0"), you need to evaluate it and return the final result. The string contains:• T and F for boolean values (true/false)
• ? and : for ternary operators
• Single digits (0-9) as values
The ternary operator works as:
condition ? valueIfTrue : valueIfFalseJust like in most programming languages, these expressions are right-associative, meaning they evaluate from right to left. For example,
"T?T?F:5:3" is grouped as "T?(T?F:5):3".Goal: Parse and evaluate the nested ternary expression to return a single character result.
Input & Output
example_1.py — Simple Ternary
$
Input:
expression = "T?2:3"
›
Output:
"2"
💡 Note:
Since the condition 'T' is true, we return the true value '2' instead of the false value '3'.
example_2.py — Nested Ternary
$
Input:
expression = "F?1:T?4:5"
›
Output:
"4"
💡 Note:
The condition 'F' is false, so we evaluate the false branch 'T?4:5'. Since 'T' is true, we return '4'.
example_3.py — Complex Nested
$
Input:
expression = "T?T?F:5:3"
›
Output:
"F"
💡 Note:
The condition 'T' is true, so we evaluate 'T?F:5'. Since the nested condition 'T' is true, we return 'F'.
Constraints
- 5 ≤ expression.length ≤ 104
- expression consists of digits, 'T', 'F', '?', and ':'
- It is guaranteed that expression is a valid ternary expression
- All numbers are single digits (0-9)
Visualization
Tap to expand
Understanding the Visualization
1
Start from Right
Begin processing from the rightmost character, pushing values onto stack
2
Encounter Question
When we see '?', we know the next two stack items are our choices
3
Make Decision
Look at the condition and pick the appropriate value
4
Continue
Push result back and continue until one value remains
Key Takeaway
🎯 Key Insight: By processing right-to-left with a stack, we naturally handle the right-associative nature of ternary expressions and evaluate them in the correct order.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code