> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Ternary Expression Parser Python Solution

> Tested Python solution for LeetCode 439 with 13 pytest cases. Generate a practice environment with lcpy.

LeetCode 439, [Medium](/catalog/medium). Topics: [Stack](/catalog/topics/stack), [Recursion](/catalog/topics/recursion), [String](/catalog/topics/string). [View on LeetCode](https://leetcode.com/problems/ternary-expression-parser/description/).

Generate this problem as a practice environment: tested reference solution, 13 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 439   # by problem number
lcpy gen -s ternary_expression_parser   # by problem name
```

## 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

```
Input: expression = "T?2:3"
Output: "2"
Explanation: If true, then result is 2; otherwise result is 3.
```

```
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".
```

```
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 : 5)" --> "F".
```

### 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](https://github.com/wislertt/leetcode-py/blob/main/leetcode/ternary_expression_parser/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/ternary_expression_parser/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(n)
    def parse_ternary(self, expression: str) -> str:
        stack: list[str] = []
        for ch in reversed(expression):
            if stack and stack[-1] == "?":
                stack.pop()
                true_val = stack.pop()
                stack.pop()  # ':'
                false_val = stack.pop()
                stack.append(true_val if ch == "T" else false_val)
            else:
                stack.append(ch)
        return stack[0]
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.