Ternary Expression Parser - Problem

Given a string expression representing arbitrarily nested ternary expressions, evaluate the expression and return the result.

You can always assume that the given expression is valid and only contains digits '0'-'9', '?', ':', 'T' (true), and 'F' (false).

Note:

  • All 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)
  • The result will always evaluate to either a digit, 'T', or 'F'

Input & Output

Example 1 — Simple Ternary
$ Input: expression = "T?2:3"
Output: "2"
💡 Note: Condition is T (true), so we return the true value which is '2'
Example 2 — Nested Ternary
$ Input: expression = "F?1:T?4:5"
Output: "4"
💡 Note: Condition is F (false), so we evaluate T?4:5. T is true, so return '4'
Example 3 — Complex Nesting
$ Input: expression = "T?T?F?1:2:3:4"
Output: "2"
💡 Note: T is true, so evaluate T?F?1:2:3. T is true, so evaluate F?1:2. F is false, so return '2'

Constraints

  • 5 ≤ expression.length ≤ 104
  • expression consists of digits, 'T', 'F', '?', and ':'
  • It is guaranteed that expression is a valid ternary expression
  • Each number in the expression is a one-digit number

Visualization

Tap to expand
Ternary Expression Parser INPUT expression = "T?2:3" T condition ? 2 if true : 3 if false Parse Tree Structure: T? 2 true 3 false Format: condition ? true_val : false_val Characters: T, F, 0-9, ?, : Groups right-to-left ALGORITHM STEPS 1 Use Stack Traverse from RIGHT to LEFT 2 Push Values Push digits, T, F to stack 3 On '?' Evaluate Pop true_val, false_val, decide 4 Return Top Final answer on stack top Stack Trace (right to left): 3 : 2 --> T=true, pick 2 push(2) FINAL RESULT Expression Evaluation: T ? 2 : 3 T is TRUE Select true branch value Output: "2" OK - Evaluation Complete Time: O(n) Space: O(n) Key Insight: Right-to-left traversal with a stack naturally handles the right-to-left grouping of ternary expressions. When we encounter '?', we pop the next two values (true_val and false_val) and push back the correct one based on whether the condition (character before '?') is 'T' or 'F'. This handles nested expressions elegantly. TutorialsPoint - Ternary Expression Parser | Optimal Stack-Based Solution
Asked in
Facebook 8 Google 5
25.0K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen