The 24 Game interview question provides you with 4 cards, each containing a number from 1 to 9. You need to determine if you can use the four basic operators and parentheses to combine these numbers to reach the value 24. Every card must be used exactly once.
This is a Hard problem frequently asked by Huawei and TikTok because it requires a perfect implementation of Backtracking and handling floating-point precision. It tests how you manage complex state spaces and edge cases (like division by zero).
The solution uses the Backtracking interview pattern. Since there are only 4 numbers, you pick any two numbers, apply one of the four operations, and replace them with the result. You then repeat this with the remaining 3 numbers, then 2, until only one number remains. If that number is approximately 24, you return true.
Input: [4, 1, 8, 7]
One way to get 24:
3 / 2 is 1. In the 24 Game, you must use doubles/floats because 3 / 2 is 1.5, which could eventually lead to 24.result == 24. Instead, check if abs(result - 24) < 1e-6.When dealing with a small, fixed number of elements (like 4 cards), backtracking is often viable even if the logic inside the recursion is dense. Always clarify if you need to return the expression or just a boolean.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Verbal Arithmetic Puzzle | Hard | Solve | |
| N-Queens | Hard | Solve | |
| Confusing Number II | Hard | Solve | |
| Three Equal Parts | Hard | Solve | |
| Combination Sum III | Medium | Solve |