Reach a Target Using Each Number At Most Once
Jane StreetSoftware Engineer · Technical ScreenLast updated
This question evaluates the ability to construct arithmetic expressions from a multiset of numbers and reason about combinatorial search, operator composition, parenthesization, and exact rational arithmetic under constraints.
Reach a Target Using Each Number At Most Once
You are given an array of integers nums and an integer target. Decide whether you can build an arithmetic expression that evaluates to exactly target, under the following rules:
- Each element of
numsmay be used at most once. Elements with equal values count as separate elements. You do not have to use every element, but you must use at least one. - The numbers you pick may be arranged in any order and combined with the binary operators
+,-,*,/, with any parenthesization. - Division is exact mathematical (rational) division: intermediate results may be non-integer fractions. Division by zero is not allowed at any step.
- No unary minus, and no concatenating digits of different numbers (e.g. you may not glue
1and2into12). - An expression consisting of a single picked number (no operators) is allowed, so if some element already equals
target, the answer istrue.
Return true if target is reachable, otherwise false. Equality must be exact (rational arithmetic), not approximate floating-point equality.
Examples
Example 1
Input: nums = [1, 2, 3, 4], target = 24
Output: true
Pick 2, 3, 4 (leaving 1 unused): 2 * 3 * 4 = 24.
Example 2
Input: nums = [3, 3, 8, 8], target = 24
Output: true
8 / (3 - 8 / 3) = 8 / (1/3) = 24. Note the intermediate values are fractions — exact rational arithmetic matters.
Example 3
Input: nums = [2, 5], target = 9
Output: false
All reachable values are 2, 5, 7, -3, 3, 10, 2/5, 5/2 — none equals 9.
Constraints
1 <= nums.length <= 50 <= nums[i] <= 100-10^4 <= target <= 10^4
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.