Skip to the code
cf.
+25 XP

#314 Every Way to Group a Formula

medium

A calculator widget shows a formula of non-negative whole numbers joined by +, -, and *, with no spaces and no brackets. A curious user wants to see what the formula could equal if brackets were added in different ways.

Write allGroupings(formula) that returns the value of every different way to fully add brackets, sorted ascending. Keep repeated values: if two different bracketings give the same value, list it twice.

Example 1

Input: formula = "3-2-1"
Output: [0,2]

(3-2)-1 = 0 and 3-(2-1) = 2.

Example 2

Input: formula = "2*3+4"
Output: [10,14]

(2*3)+4 = 10 and 2*(3+4) = 14.

Constraints

  • 1 <= formula.length <= 20
  • The formula has at most 7 operators.
  • Numbers are between 0 and 99.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).