Skip to main content
impol.dev

Editorial

Solution walkthrough

Review the explanation, then compare the reference implementation.

Video explanation

Solution

Intuition

Any fully parenthesized expression can be evaluated by repeatedly combining two available values into one. Searching over those pairwise combinations therefore covers every legal parenthesization, including expressions that need fractional or negative intermediate values.

Approach

  1. Recursively choose two distinct positions from the current list. Preserve all other values in a new list.
  2. Try replacing the pair with its sum, product, both subtraction orders, and both division orders. Skip division when its denominator is zero. Each replacement consumes exactly the two chosen expressions, so no card is reused or omitted.
  3. When only one value remains, check whether it is sufficiently close to 24 using the implementation's floating-point tolerance. Exact equality could reject a valid expression after rounding.
  4. Return true on the first successful branch and false if all combinations fail. Some equivalent branches are explored more than once, which is acceptable for the fixed four-card input.
class Solution: def judgePoint24(self, cards: List[int]) -> bool: def dfs(nums): if len(nums) == 1: return isclose(nums[0], 24) n = len(nums) for i in range(n): for j in range(n): if i != j: base = [nums[k] for k in range(n) if k != i and k != j] if dfs(base + [nums[i] + nums[j]]): return True if dfs(base + [nums[i] - nums[j]]): return True if dfs(base + [nums[i] * nums[j]]): return True if nums[j] != 0 and dfs(base + [nums[i] / nums[j]]): return True if dfs(base + [nums[j] - nums[i]]): return True if nums[i] != 0 and dfs(base + [nums[j] / nums[i]]): return True return False return dfs(cards)

Complexity analysis

The problem always supplies four cards, so time and auxiliary space are O(1) with respect to the fixed input size. Generalized to n cards, time is O(6^(n-1)·n!·(n-1)!) recursive branches and auxiliary space is O(n²) for active recursion/lists.