Magicsheet logo

24 Game

Hard
61.3%
Updated 6/1/2025

24 Game

What is this problem about?

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 (+,,×,/)(+, -, \times, /) and parentheses to combine these numbers to reach the value 24. Every card must be used exactly once.

Why is this asked in interviews?

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).

Algorithmic pattern used

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.

Example explanation

Input: [4, 1, 8, 7] One way to get 24:

  1. 8/(1(2/3))8 / (1 - (2/3)) ... wait, let's use a simpler one:
  2. (84)×(71)4×6=24(8 - 4) \times (7 - 1) \rightarrow 4 \times 6 = 24. The algorithm explores all combinations of pairs and operators until it finds this path or exhausts all options.

Common mistakes candidates make

  • Integer Division: In many languages, 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.
  • Precision errors: Due to floating-point math, you shouldn't check result == 24. Instead, check if abs(result - 24) < 1e-6.
  • Missing Permutations: Forgetting that the order of subtraction and division matters (aba - b is not the same as bab - a).

Interview preparation tip

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.

Similar Questions