LeetCode 439, Medium. Topics: Stack, Recursion, String. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 13 parametrized pytest cases, and a playground notebook:
Problem
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'.
Examples
Constraints
5 <= expression.length <= 10^4.
expression consists of digits, '?', ':', 'T', and 'F'.
- It is guaranteed that
expression is a valid ternary expression and that each number is a one-digit number.
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026