Google questions

Target Expressions

GoogleHard

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.

Part 1: Three digits

Given digits containing exactly 3 digits and an integer target, return the canonical text of every distinct expression whose value equals target, sorted in ascending order as ordinary strings. If no expression equals target, return an empty list.

  1. Example 1
    digits
    [2,3,4]
    target
    14
    Output
    ["2*(3+4)","2+3*4"]

    Why: 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.

Constraints

  • len(digits) == 3
  • 0 <= digits[i] <= 9
  • 0 <= target <= 10^9
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Target Expressions: Google interview question | LoopCoach