All problems
0588HardArrayMathBacktracking

Four Chips to Twenty-Four

Tracked in this browser only
Write code

Trains the technique from

LeetCode 67924 Game

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A tabletop puzzle deals four numbered chips, given in cards, each showing a digit from 1 to 9.

The aim is to write an arithmetic line worth exactly 24 under these rules:

  • Each chip's number is used once and once only. The chips may be taken in any order.
  • The four numbers are joined by three operators, each chosen freely from +, -, * and /, and brackets may be placed however you like.
  • Division is ordinary division, not whole-number division, so a partial value such as one third is perfectly legal as long as the line finishes at 24. Dividing by zero is not allowed, and a zero can turn up as a partial value, for instance from a chip subtracted from an equal chip.
  • No two chips may be written side by side to make a two-digit number, and no number may be given a leading minus sign of its own.

All arithmetic is exact, and the line has to come to 24 exactly rather than close to it. Return true when such a line exists and false otherwise.

Examples

Example 1

Input
cards = [5, 5, 5, 1]
Output
true

The line 5 * (5 - 1 / 5) is worth 24, since 1 / 5 is one fifth, 5 minus one fifth is four and four fifths, and five times that is 24.

Example 2

Input
cards = [1, 1, 1, 1]
Output
false

Every line that can be written from four ones is worth at most 4, so 24 is out of reach.

Example 3

Input
cards = [1, 2, 3, 4]
Output
true

The line 1 * 2 * 3 * 4 is worth 24.

Constraints

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

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def judge_point24(cards: list[int]) -> bool:
Java
public boolean judgePoint24(int[] cards)
September 7
Apply