24 Game - 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.

Input & Output

Example 1 — Valid 24 Game
$ Input: cards = [4,1,8,7]
Output: true
💡 Note: We can form (8-4) * (7-1) = 4 * 6 = 24
Example 2 — Invalid 24 Game
$ Input: cards = [1,2,1,2]
Output: false
💡 Note: No valid combination of operations can produce 24 from these numbers
Example 3 — Division Required
$ Input: cards = [3,3,8,8]
Output: true
💡 Note: We can form (8/(3-8/3)) = 8/(3-8/3) = 8/(1/3) = 24

Constraints

  • cards.length == 4
  • 1 ≤ cards[i] ≤ 9

Visualization

Tap to expand
24 Game: Combine 4 Numbers to Make 244187Input CardsTry different combinations:(8-4) × (7-1) = 4 × 6 = 24 ✓Output:trueOperations: +, -, ×, ÷ with parentheses allowedGoal: Find ANY combination that equals 24
Understanding the Visualization
1
Input
4 cards with numbers [4,1,8,7]
2
Process
Try all combinations of +, -, *, / with different groupings
3
Output
Return true if any combination equals 24
Key Takeaway
🎯 Key Insight: Use backtracking to systematically try all possible combinations of operations and groupings
Asked in
Google 25 Microsoft 20 Amazon 15
32.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen