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: T?2:F?3:1T ? 2 : F ? 3 : 1Right-associative: T ? 2 : (F ? 3 : 1)Condition: TTrue Branch: 2False Branch: F?3:1Condition: FTrue Branch: 3False Branch: 1T is TRUE2Final Result: 2
Understanding the Visualization
1
Input Expression
T?2:F?3:1 - nested ternary with right-associativity
2
Parse Structure
T ? 2 : (F ? 3 : 1) - parentheses show precedence
3
Evaluate
T is true, so result is 2
Key Takeaway
🎯 Key Insight: Ternary expressions are right-associative, so we need to handle precedence correctly using stack or recursion
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