Four Numbers, One Target: Arithmetic Reachability
Math & Bit ManipulationAuto-graded · 23 test casesLast updated
Tests combinatorial search over arithmetic expressions, exact rational arithmetic, and division-by-zero handling to decide if four numbers can combine to a target.
Problem
You receive a list of exactly four integers and a target value. Your task is to decide whether the four integers can be combined — using addition, subtraction, multiplication, and division, along with any arrangement of parentheses — to produce a result equal to the target.
Each integer must be used exactly once. You may apply the four basic operators (+, -, *, /) in any order and group sub-expressions with parentheses however you like.
Return True if such an expression exists, False otherwise.
Rules and clarifications
- Exact length: if
numbersdoes not contain exactly four elements, returnFalse. - Each number used once: every element of
numbersis consumed exactly once in the expression. - Division by zero: dividing by a value that equals zero is not a legal operation. Skip any branch where the divisor is zero; do not return infinity or raise an error.
- Floating-point: intermediate results may be non-integer fractions (e.g.,
8/3). Use exact rational arithmetic so that expressions like8 / (3 - 8/3)are evaluated without rounding error. - Negative numbers and zero as inputs are permitted; the same rules apply.
- Unary minus and digit concatenation are not allowed.
Constraints
len(numbers) == 4(any other length →False)-100 <= numbers[i] <= 100numbers[i]is an integer-1000 <= target <= 1000targetis an integer
Examples
Example 1
Input: can_reach_target([4, 1, 8, 7], 24)
Output: True
Example 2
Input: can_reach_target([1, 2, 3, 4], 24)
Output: True
Example 3
Input: can_reach_target([1, 1, 1, 1], 24)
Output: False
Hints
Hint 1
Instead of enumerating expression strings, think of the problem as repeatedly merging two numbers into one result. After three merges, a single number remains — check if it equals the target.
Hint 2
For each merge step, try every unordered pair of current values and every applicable operator (both directions for subtraction and division). This covers all possible tree shapes without explicitly tracking parenthesizations.
Hint 3
Use Python's `fractions.Fraction` for all arithmetic. It keeps intermediate values exact, so an expression like 8 / (3 − 8/3) won't silently evaluate to 23.9999… instead of 24.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is that any fully-parenthesized arithmetic expression over four numbers is a binary tree. The root of that tree combines two sub-results with a single operator. Instead of enumerating expression strings — which is complicated by all possible parenthesizations — we can model the problem as a sequence of merges:
- Start with a list of four values.
- Pick any unordered pair, remove both, and replace them with the result of applying one operator. For subtraction and division, try both orderings (
a - bandb - a, etc.). - Recurse on the three-element list.
- Repeat until one value remains. Check whether it equals the target.
Choosing any unordered pair at each step naturally explores every possible binary tree shape, including balanced trees like (a op b) op (c op d) and left/right-skewed chains like ((a op b) op c) op d. No tree is missed.
Why it is correct
Completeness: given any valid expression tree, its deepest internal node merges two leaves. That merge is one candidate the search considers. After the merge, the problem reduces to three values, and the same argument applies by induction. Every expression is therefore reached.
Soundness: every branch applies a legal operator to values already in the list. Each original number is consumed exactly once because merged items are removed. Any final value equal to the target therefore corresponds to a valid expression.
Handling numeric edge cases
Division by zero is handled by checking b != 0 or a != 0 before adding those candidates. Illegal branches are simply skipped.
Floating-point rounding is eliminated by using fractions.Fraction throughout. The classic trap is 8 / (3 - 8/3) = 24: in floating point 8/3 is inexact and the result may be 23.999999.... With Fraction, every intermediate value is exact, so equality checks are reliable.
Complexity
For four numbers, the search tree has at most:
| Values left | Unordered pairs | Operations per pair | Branches |
|---|---|---|---|
| 4 | 6 | 6 | 36 |
| 3 | 3 | 6 | 18 |
| 2 | 1 | 6 | 6 |
Maximum leaf evaluations: 36 × 18 × 6 = 3,888 — effectively O(1) for this fixed input size.
- Time: constant; each node does a fixed amount of work on small
Fractionobjects. - Space: recursion depth is 3; each level holds at most 4 items. O(1) beyond the input.
Edge cases
len(numbers) != 4→ returnFalseimmediately.- Zero as a divisor → that branch is skipped.
- Negative inputs or target →
Fractionhandles signs exactly. - Duplicate values (e.g.,
[1,1,1,1]) → correct but causes some redundant work. - Fractional intermediates (e.g.,
[1,5,5,5]→5*(5 - 1/5) = 24) → handled correctly becauseFractiontracks non-integer intermediates exactly.
Reference Solution
from fractions import Fraction
from typing import List
def can_reach_target(numbers: List[int], target: int) -> bool:
if len(numbers) != 4:
return False
goal = Fraction(target)
def search(items):
# items: list of (Fraction value, expression string)
if len(items) == 1:
return items[0][0] == goal
for i in range(len(items)):
for j in range(i + 1, len(items)):
a, ea = items[i]
b, eb = items[j]
rest = [items[k] for k in range(len(items)) if k != i and k != j]
# All six operator applications (both directions for - and /)
candidates = [
(a + b, f"({ea}+{eb})"),
(a - b, f"({ea}-{eb})"),
(b - a, f"({eb}-{ea})"),
(a * b, f"({ea}*{eb})"),
]
if b != 0:
candidates.append((a / b, f"({ea}/{eb})"))
if a != 0:
candidates.append((b / a, f"({eb}/{ea})"))
for value, expr in candidates:
if search(rest + [(value, expr)]):
return True
return False
initial = [(Fraction(n), str(n)) for n in numbers]
return search(initial)
Each item carries its expression string alongside its numeric value. The string is unused by the boolean return but makes it trivial to extend the function to also report a valid expression when one is found.