Expression Add Operators

HardBacktrackingbacktracking

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a string num of digits and an integer target. Between any two adjacent digits you may insert +, -, *, or nothing (which joins the digits into a longer operand). Return every resulting expression that evaluates to target using normal precedence (* before + and -). Operands must not have leading zeros: "05" is not allowed as an operand, but "0" by itself is. No unary minus may be added before the first digit. Return the expressions in any order; each distinct expression string appears once.

Examples

Input: num = "123", target = 6
Output: ["1*2*3","1+2+3"]
Both expressions evaluate to 6.
Input: num = "232", target = 8
Output: ["2*3+2","2+3*2"]
2*3+2 = 8 and 2+3*2 = 8.
Input: num = "105", target = 5
Output: ["1*0+5","10-5"]
"1*05" is not allowed because the operand 05 has a leading zero.

Constraints

  • 1 <= num.length <= 10
  • `num` consists only of digits
  • -2^31 <= target <= 2^31 - 1

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More backtracking problems