Problem 679

Abstract / Summary

Given four numbers and basic arithmetic operations can you make the value 24 using each number once

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0679.py

class Solution:
    def judgePoint24(self, cards: List[int]) -> bool:
        # a,b,c are placeholders for operations
        def calc(formula):
            ops = [ "+", "-", "*", "/" ]
            for a in ops:
                for b in ops:
                    for c in ops:
                        f = formula
                        f = f.replace("a", a)
                        f = f.replace("b", b)
                        f = f.replace("c", c)
                        try:
                            if abs(eval(f) - 24) < 0.0000001: # allow small rounding errors
                                return True
                        except ZeroDivisionError:
                            continue
            return False


        s = [ str(c) for c in cards]
        for n in permutations(s):
            # ten distinct possibilities to add brackets
            if calc(n[0] + "a" + n[1] + "b" + n[2] + "c" + n[3]):
                return True
            if calc("(" + n[0] + "a" + n[1] + ")b" + n[2] + "c" + n[3]):
                return True
            if calc(n[0] + "a(" + n[1] + "b" + n[2] + ")c" + n[3]):
                return True
            if calc(n[0] + "a" + n[1] + "b(" + n[2] + "c" + n[3] + ")"):
                return True
            if calc("(" + n[0] + "a" + n[1] + ")b(" + n[2] + "c" + n[3] + ")"):
                return True
            if calc(n[0] + "a(" + n[1] + "b" + n[2] + "c" + n[3] + ")"):
                return True
            if calc(n[0] + "a((" + n[1] + "b" + n[2] + ")c" + n[3] + ")"):
                return True
            if calc(n[0] + "a(" + n[1] + "b(" + n[2] + "c" + n[3] + "))"):
                return True
            if calc("((" + n[0] + "a" + n[1] + ")b" + n[2] + ")c" + n[3]):
                return True
            if calc("(" + n[0] + "a(" + n[1] + "b" + n[2] + "))c" + n[3]):
                return True

        return False
45 lines | 1937 bytes | submitted September 10, 2023 | GitHub   7% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation determines whether four given integers can be combined with the basic arithmetic operators to produce the value 24. It exhaustively explores every ordering of the numbers, every choice of three operators, and a curated set of ten distinct parenthesization patterns. For each constructed expression it evaluates the result, tolerating minor floating-point inaccuracies, and returns True as soon as a valid expression is found; otherwise it returns False.

Key Steps

The algorithm begins by converting each integer card into its string representation so that later string concatenation can build arithmetic formulas.

s = [str(c) for c in cards]

A helper function calc receives a formula string containing placeholder characters a, b, and c. It iterates over the four basic operators, substitutes each placeholder with a concrete operator, and evaluates the resulting expression with Python’s eval. A try/except block catches division-by-zero attempts, allowing the search to continue uninterrupted. The function returns True the moment an expression evaluates to a value whose absolute difference from 24 is less than 1e-7.

def calc(formula):
    ops = ["+", "-", "*", "/"]
    for a in ops:
        for b in ops:
            for c in ops:
                f = formula.replace("a", a).replace("b", b).replace("c", c)
                try:
                    if abs(eval(f) - 24) < 0.0000001:
                        return True
                except ZeroDivisionError:
                    continue
    return False

The core loop enumerates every permutation of the four stringified cards using itertools.permutations. For each ordering, the code constructs ten distinct parenthesized expressions that cover all meaningful binary tree shapes for four operands. Each expression is passed to calc; if any call succeeds, the outer function returns True immediately.

for n in permutations(s):
    if calc(n[0] + "a" + n[1] + "b" + n[2] + "c" + n[3]):
        return True
    if calc("(" + n[0] + "a" + n[1] + ")b" + n[2] + "c" + n[3]):
        return True
    if calc(n[0] + "a(" + n[1] + "b" + n[2] + ")c" + n[3]):
        return True
    if calc(n[0] + "a" + n[1] + "b(" + n[2] + "c" + n[3] + ")"):
        return True
    if calc("(" + n[0] + "a" + n[1] + ")b(" + n[2] + "c" + n[3] + ")"):
        return True
    if calc(n[0] + "a(" + n[1] + "b" + n[2] + "c" + n[3] + ")"):
        return True
    if calc(n[0] + "a((" + n[1] + "b" + n[2] + ")c" + n[3] + ")"):
        return True
    if calc(n[0] + "a(" + n[1] + "b(" + n[2] + "c" + n[3] + "))"):
        return True
    if calc("((" + n[0] + "a" + n[1] + ")b" + n[2] + ")c" + n[3]):
        return True
    if calc("(" + n[0] + "a(" + n[1] + "b" + n[2] + "))c" + n[3]):
        return True

If none of the generated formulas yield 24, the function concludes that the cards cannot form the target and returns False.

Edge Cases Handled

Division by zero is a natural possibility when the operator set includes /. The calc function wraps each eval call in a try/except block that specifically catches ZeroDivisionError and simply proceeds to the next operator combination, ensuring that a single illegal intermediate expression does not abort the entire search.

Floating-point rounding errors are mitigated by comparing the absolute difference between the evaluated result and 24 against a very small epsilon (1e-7). This tolerance allows expressions that mathematically equal 24 but suffer from binary representation imprecision to be accepted.

The permutation step treats each card as a distinct element even if values repeat, guaranteeing that all positional variations are examined. The ten parenthesization patterns cover every binary tree shape for four operands, so the algorithm does not miss any valid grouping that could produce 24.

Performance Optimizations

The search space is bounded by three factors: 24 permutations of the cards, 64 possible operator triples (4³), and ten parenthesization templates. By nesting the loops in this order, the code evaluates at most 24 × 10 × 64 = 15,360 expressions, a modest count for modern processors.

Early termination is built into both the calc function and the outer permutation loop. As soon as an expression satisfies the target, calc returns True, causing the surrounding if statement to exit the current permutation iteration. Likewise, the outer loop returns True immediately, preventing any further permutations from being generated.

String substitution is performed with chained replace calls on a single copy of the formula, avoiding the creation of intermediate strings for each placeholder. This reduces allocation overhead during the intensive inner loops.

Using Python’s built-in eval leverages the interpreter’s optimized arithmetic evaluation rather than implementing a custom expression parser, which keeps the per-evaluation cost low.

Overall, the combination of bounded combinatorial enumeration, early exits, and lightweight string handling yields a solution that runs quickly despite its exhaustive nature.

written by openai gpt

ELI5 - Simplified Explanation

Imagine having four number cards and wanting to play a game where the goal is to make the number twenty-four. This code acts like a very fast robot friend that helps with that game. First, the robot looks at all the different ways the four cards can be put in a row. It is like shuffling playing cards to see which order looks best. After picking an order, the robot tries every possible way to put math signs like plus, minus, multiply, and divide between the numbers.

The robot also uses special shapes called parentheses to decide which numbers to add or multiply first, just like deciding which pieces of a puzzle to snap together first. Because computers sometimes get slightly confused with decimals, the robot checks if the answer is really close to twenty-four to make sure it is not missing a win. If the robot finds any combination that makes twenty-four, it stops and says it found a way to win. It keeps trying every single possibility until there are no combinations left to check. This is a very thorough way to make sure no winning patterns are missed.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 4 | μ = 4.00 | σ = 1.62

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Go Java Rust TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github everthis JS
fengvyi C++
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
everthis JavaScript
fengvyi C++
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
wisdompeak C++
zfang399 C++
30 links | 15 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

6 solutions   September 10, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality