Target Expressions

Asked at Google

Reported by the problem's creator, not verified

You are given a list of digits, each from 0 to 9, and an integer target. An expression combines the digits in the given order, using each one exactly once as its own operand — digits are never merged into multi-digit numbers. Between consecutive digits you place either + or *, and you may add parentheses around any group. Without parentheses, * is applied before +.

Every expression is written in a canonical text: no spaces, and the only parentheses kept are those whose removal would change the value — a sum that serves as an operand of * keeps them. So 2+(3*4) is written 2+3*4, 2*(3+4) keeps its parentheses, and 2+(3+4) and (2+3)+4 both become 2+3+4, counting as one expression.

Examples

  1. Example 1

    Input: digits = [2,3,4], target = 14

    Output: ["2*(3+4)","2+3*4"]

    Explanation: 2*(3+4) groups the sum first and evaluates to 14; 2+3*4 also evaluates to 14 because * binds tighter, so it needs no parentheses. Both canonical texts are distinct and sort in this order.

Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question

Code

Loading editor…

Ln 1, Col 1

Start an attempt to use Coach.