Interview conceptCoding & Algorithms

Combinatorial Search With Exact Arithmetic

Asked of: Software Engineer

Last updated

Horizontal trace of subset search: choose unordered pairs, apply exact fraction operations, reduce the multiset, memoize canonical states, and detect target 24.

What's being tested

This tests combinatorial search over subsets of numbers, with recursive operator composition and parenthesization. You must control duplicate states, handle division and subtraction correctly, and use exact rational arithmetic rather than floating-point comparisons.

Patterns & templates

  • Enumerate unordered pairs of current values, apply each operator, then recurse on the reduced multiset; this naturally explores every parenthesization.

  • Represent values as reduced fractions, such as (numerator, denominator), using gcd; test equality with cross-multiplication or canonical pairs.

  • Preserve subtraction and division direction: for values a, b, consider both a-b and b-a, plus a/b and b/a when denominators are nonzero.

  • Memoize canonical multiset states, sorting fraction pairs after each reduction; this removes duplicate work caused by operand order and repeated inputs.

  • Decide whether numbers may be skipped: “at most once” permits unused values, so check the target at every recursive state or add a subset dimension.

  • With n numbers, pair-reduction search is exponential; memoization helps substantially, while unrestricted expression enumeration remains infeasible for large n.

  • Guard arithmetic edge cases explicitly: division by zero, negative intermediates, zero targets, repeated numbers, and fractions that must be normalized after every operation.

Common pitfalls

Pitfall: Using float and checking abs(x - target) < epsilon can accept incorrect expressions or reject exact results.

Pitfall: Exploring only a-b and a/b misses valid expressions because those operators are not commutative.

Pitfall: Assuming every number must be used changes “at most once” into “exactly once”; clarify this before choosing the recursion state.

Practice these

The practice cards below cover the canonical variants — solve all of them and time yourself.

Practice questions

Related concepts