Insert +, -, * and Parentheses Between Ordered Numbers to Reach a Target
Company: Waymo
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Given numbers in a fixed order and a target, insert +, - or * between them and add parentheses to reach the target, returning the lexicographically smallest fully parenthesized expression or an empty string. Starts with three numbers and generalizes to n, testing exhaustive search over expression trees.
Constraints
- 1 <= len(nums) <= 6
- 0 <= nums[i] <= 50
- -10^11 <= target <= 10^11
- Every intermediate and final value of every expression lies within [-10^11, 10^11], so 64-bit integers are sufficient (target and computed values can exceed 2^31 - 1).
- For len(nums) == 1, the only expression is the number itself.
Examples
Input: ([2, 3, 4], 14)
Expected Output: '(2*(3+4))'
Explanation: Example 1: (2*(3+4)) and (2+(3*4)) both give 14; '*' sorts before '+' at the third character.
Input: ([8, 3, 5, 2], 1)
Expected Output: '((8+3)-(5*2))'
Explanation: Example 2: ((8+3)-(5*2)) beats (8+(3-(5*2))) because '(' sorts before every digit.
Hints
- Look at the operator that is applied last: it splits the numbers into a contiguous left block and a contiguous right block, and each block is a smaller expression of the same kind.
- Every canonical expression over the same contiguous block has exactly the same length. What does that imply when you compare two combined strings that share a split point and an operator?
- With at most six numbers there are only 42 * 3^5 = 10,206 expressions in total, so exploring all of them is fast enough; the real work is getting the tie-break right.