Different Ways to Add Parentheses

MediumDynamic Programminginterval dp

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 expression made of non-negative integers joined by the binary operators +, - and * (no spaces, no parentheses, no unary minus). Consider every distinct way to fully parenthesize the expression, meaning every distinct binary evaluation tree over its operands in their original order. Evaluate each one and return all the results. Return the values in **any order**. If two different groupings produce the same number, that number appears once per grouping (duplicates are kept).

Examples

Input: expression = "2-1-1"
Output: [0,2]
((2-1)-1) = 0 and (2-(1-1)) = 2.
Input: expression = "2*3-4*5"
Output: [-34,-14,-10,-10,10]
(2*(3-(4*5))) = -34, ((2*3)-(4*5)) = -14, ((2*(3-4))*5) = -10, (2*((3-4)*5)) = -10, (((2*3)-4)*5) = 10.

Constraints

  • 1 <= expression.length <= 20
  • Operands are integers in [0, 99] with no leading zeros
  • expression contains only digits and '+', '-', '*'
  • Every result fits in a 32-bit signed integer

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 interval dp problems