24 Game - Problem
Imagine you're a mathematician with four number cards in your hand, each showing a digit from 1 to 9. Your challenge? Combine these numbers using basic arithmetic operations (+, -, *, /) and parentheses to create an expression that equals exactly 24!
This is the classic 24 Game - a popular mathematical puzzle that tests your ability to think creatively with numbers. You have complete freedom to:
- ๐ Rearrange the numbers in any order
- ๐งฎ Use any combination of the four basic operations
- ๐ Group operations with parentheses however you like
Rules to remember:
- Division represents real division, not integer division (so 4 รท 3 = 1.333...)
- Every operation must be between two numbers - no unary minus allowed
- You cannot concatenate digits (no combining 1 and 2 to make 12)
- You must use all four cards exactly once
Return true if you can create a valid expression that equals 24, false otherwise.
Input & Output
example_1.py โ Basic Success Case
$
Input:
[4, 1, 8, 7]
โบ
Output:
true
๐ก Note:
We can create (8-4) ร (7-1) = 4 ร 6 = 24, so this returns true.
example_2.py โ Impossible Case
$
Input:
[1, 1, 1, 1]
โบ
Output:
false
๐ก Note:
No matter how we combine four 1's with basic operations, we cannot reach 24. The maximum we can get is 1+1+1+1=4.
example_3.py โ Division Required
$
Input:
[1, 2, 1, 2]
โบ
Output:
false
๐ก Note:
Even with operations like (1+1) ร (2+2) = 8 or (1ร2) + (1ร2) = 4, we cannot reach 24 with these numbers.
Constraints
- cards.length == 4
- 1 โค cards[i] โค 9
- Precision requirement: Consider two numbers equal if their difference is less than 10-6
Visualization
Tap to expand
Understanding the Visualization
1
Root: 4 Numbers
Start with all four cards: [4,1,8,7]
2
Level 1: Choose First Pair
Pick any 2 numbers to combine first (6 ways to choose pairs)
3
Level 2: Apply Operations
For each pair, try +, -, *, / operations (up to 6 operations considering order)
4
Level 3: Recurse with 3 Numbers
Continue with result plus 2 remaining numbers
5
Leaf: Check Result
When 1 number remains, check if it equals 24
Key Takeaway
๐ฏ Key Insight: With only 4 numbers, we can afford to try every possible combination systematically. The recursive backtracking explores all ~1500 possibilities efficiently, guaranteeing we find a solution if one exists!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code