KatInterview

Four Numbers, One Target: Arithmetic Reachability

Math & Bit ManipulationAuto-graded · 23 test cases
MediumAuto-gradedMath & Bit Manipulationbacktrackingrecursionmath

Last 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 numbers does not contain exactly four elements, return False.
  • Each number used once: every element of numbers is 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 like 8 / (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] <= 100
  • numbers[i] is an integer
  • -1000 <= target <= 1000
  • target is 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.