Ctrl K

Reach Twenty-Four

Hard
You were dealt four cards with the numbers cards. Build an arithmetic expression from them whose value is exactly 24. Use every card exactly once, in any order. Rules: - you may use +, -, *, / and as many parentheses as you like; - division is real, not integer: for example, 4 / (1 − 2 / 3) = 12; - every operation takes two numbers, so there is no unary minus: -1 - 1 - 1 - 1 is not allowed; - cards cannot be glued into multi-digit numbers: 1 and 2 do not make 12. Return True if such an expression exists, and False otherwise.
Example 1
cards=[3, 3, 8, 8] → True

8 / (3 − 8 / 3) = 8 / (1/3) = 24. Fractions are unavoidable here.

Example 2
cards=[1, 1, 1, 1] → False

Four ones cannot give more than 4: the best is (1 + 1) · (1 + 1) = 4.

Example 3
cards=[2, 3, 4, 1] → True

(1 + 2 + 3) · 4 = 24.

Constraints
  • len(cards) = 4
  • 1 ≤ cards[i] ≤ 13
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSquare-Sum Chains HardLetter Sum Cipher HardA Fair Split of Colored Beads HardXOR of Every Subset EasyFewest Lines Through the Dots Medium
loading Python…
Input
cards=[3, 3, 8, 8]
Expected
True

Run checks the first 3 tests in your browser. Submit checks all 112 tests on the server, hidden ones included.