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

# 24 Game Python Solution with Tests

> Tested Python solution for LeetCode 679 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 679, [Hard](/catalog/hard). Topics: [Array](/catalog/topics/array), [Math](/catalog/topics/math), [Backtracking](/catalog/topics/backtracking). [View on LeetCode](https://leetcode.com/problems/game-24/description/).

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

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

## Problem

You are given an integer array `cards` of length `4`. You have four cards, each containing a number in the range `[1, 9]`. You should arrange the numbers on these cards in a mathematical expression using the operators `['+', '-', '*', '/']` and the parentheses `'('` and `')'` to get the value 24.

You are restricted with the following rules:

* The division operator `'/'` represents real division, not integer division.
  * For example, `4 / (1 - 2 / 3) = 4 / (1 / 3) = 12`.
* Every operation done is between two numbers. In particular, we cannot use `'-'` as a unary operator.
  * For example, if `cards = [1, 1, 1, 1]`, the expression `"-1 - 1 - 1 - 1"` is **not allowed**.
* You cannot concatenate numbers together
  * For example, if `cards = [1, 2, 1, 2]`, the expression `"12 + 12"` is not valid.

Return `true` if you can get such expression that evaluates to 24, and `false` otherwise.

### Examples

```
Input: cards = [4,1,8,7]
Output: true
Explanation: (8-4) * (7-1) = 24
```

```
Input: cards = [1,2,1,2]
Output: false
```

### Constraints

* cards.length == 4
* 1 \<= cards\[i] \<= 9

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/game_24/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/game_24/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from fractions import Fraction


class Solution:
    # Time: O(n^3 * 4^(n-1)) with n = 4, a constant bounded by ~6 * 4^5 pairings
    # Space: O(4^2) for the memoized intermediate states
    def judge_point24(self, cards: list[int]) -> bool:
        memo: dict[tuple[Fraction, ...], bool] = {}

        def search(values: tuple[Fraction, ...]) -> bool:
            if len(values) == 1:
                return values[0] == Fraction(24)
            cached = memo.get(values)
            if cached is not None:
                return cached
            n = len(values)
            result = False
            for i in range(n):
                for j in range(n):
                    if i == j:
                        continue
                    rest = [values[k] for k in range(n) if k not in (i, j)]
                    a, b = values[i], values[j]
                    results = [a + b, a - b, a * b]
                    if b != 0:
                        results.append(a / b)
                    if any(search((*rest, nxt)) for nxt in results):
                        result = True
                        break
                if result:
                    break
            memo[values] = result
            return result

        return search(tuple(Fraction(card) for card in cards))
```

## Complexity

| Time | Space |
| - | - |
| O(n^3 \* 4^(n-1)) with n = 4, a constant bounded by \~6 \* 4^5 pairings | O(4^2) for the memoized intermediate states |

## Tags


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