Leetcode #679: 24 Game
In this guide, we solve Leetcode #679 24 Game in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9].
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Array, Math, Backtracking
Intuition
We must explore combinations of choices, but many branches can be pruned early.
Backtracking enumerates valid candidates while keeping the search space under control.
Approach
Use DFS to build candidates step by step, and backtrack when constraints are violated.
Pruning keeps the exploration practical for typical constraints.
Steps:
- Define the decision tree.
- DFS through choices and backtrack.
- Prune invalid paths early.
Example
Input: cards = [4,1,8,7]
Output: true
Explanation: (8-4) * (7-1) = 24
Python Solution
class Solution:
def judgePoint24(self, cards: List[int]) -> bool:
def dfs(nums: List[float]):
n = len(nums)
if n == 1:
if abs(nums[0] - 24) < 1e-6:
return True
return False
ok = False
for i in range(n):
for j in range(n):
if i != j:
nxt = [nums[k] for k in range(n) if k != i and k != j]
for op in ops:
match op:
case "/":
if nums[j] == 0:
continue
ok |= dfs(nxt + [nums[i] / nums[j]])
case "*":
ok |= dfs(nxt + [nums[i] * nums[j]])
case "+":
ok |= dfs(nxt + [nums[i] + nums[j]])
case "-":
ok |= dfs(nxt + [nums[i] - nums[j]])
if ok:
return True
return ok
ops = ("+", "-", "*", "/")
nums = [float(x) for x in cards]
return dfs(nums)
Complexity
The time complexity is Exponential (worst case). The space complexity is O(depth).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.