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 - Optimal Solution INPUT Four cards array: 4 1 8 7 Available operators: + - * / Target value: 24 cards = [4, 1, 8, 7] ALGORITHM STEPS 1 Recursive Backtrack Try all pairs of numbers 2 Apply Operations +, -, *, / on each pair 3 Reduce Array Replace pair with result 4 Check Result Is final value == 24? Example Path: [4,1,8,7] 8 - 1 = 7 --> [4,7,7] 7 - 4 = 3 --> [7,3] 7 * 3 = 21... try other (8-4)*(7-1) = 4*6 = 24 FINAL RESULT OK Solution Found! (8 - 4) * (7 - 1) = 4 * 6 = 24 return true 24 can be achieved with the given cards! Key Insight: Use recursive backtracking to try ALL combinations: pick any 2 numbers, apply each operator, replace with result, and recurse. With 4 numbers, there are only ~9216 possible expressions. Use epsilon (1e-6) for floating-point comparison when checking if result equals 24. TutorialsPoint - 24 Game | Optimal Backtracking Approach
Asked in
Google 25 Microsoft 20 Amazon 15
32.3K 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