Determine and print expression to reach target
Company: Snapchat
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: This question evaluates skill in constructing and evaluating arithmetic expressions, handling numerical stability (including division-by-zero and floating-point tolerance), and reasoning about combinatorial permutations of numbers and operators.
Constraints
- Each number in nums must be used exactly once.
- Allowed operators: + - * / and parentheses (any grouping).
- Intermediate and final values are compared with a floating-point tolerance of 1e-6.
- Division is only permitted when the divisor's absolute value exceeds 1e-6 (no division by zero).
- An empty nums list returns false.
Examples
Input: ([4, 1, 8, 7], 24)
Expected Output: True
Explanation: (8 - 4) * (7 - 1) = 4 * 6 = 24, so the target is reachable.
Input: ([1, 2, 1, 2], 24)
Expected Output: False
Explanation: No combination of 1, 2, 1, 2 with + - * / reaches 24.
Input: ([3, 3, 8, 8], 24)
Expected Output: True
Explanation: 8 / (3 - 8 / 3) = 8 / (1/3) = 24, the well-known hard 24-game case.
Input: ([1, 5, 5, 5], 24)
Expected Output: True
Explanation: 5 * (5 - 1/5) = 5 * 4.8 = 24, exercising fractional intermediate values.
Input: ([1, 1, 1, 1], 24)
Expected Output: False
Explanation: Only 1s cannot be combined to reach 24.
Input: ([2, 7, 11, 15], 9)
Expected Output: True
Explanation: A combination such as (15 - 11) + 7 - 2 = 9 reaches the target.
Input: ([5], 5)
Expected Output: True
Explanation: A single number reaches the target only when it equals the target.
Input: ([], 24)
Expected Output: False
Explanation: Empty input cannot form any expression, so the answer is false.
Input: ([6, 6, 6, 6], 24)
Expected Output: True
Explanation: 6 + 6 + 6 + 6 = 24.
Input: ([1, 2, 3], 7)
Expected Output: True
Explanation: Generalizes beyond four numbers: 1 + 2 * 3 = 7.
Hints
- Think of the problem as repeatedly replacing two values by the result of one operation, until a single value remains; if that value equals the target (within tolerance) you've found an expression.
- Try every ordered pair (a, b) so that both a-b and b-a, and a/b and b/a, are explored. Guard division by checking |b| > 1e-6.
- Use a small epsilon (1e-6) for all equality and division-by-zero checks, because intermediate division can produce non-integers.