Skip to the code
+50 XP

#290 Spreadsheet Formula Search

hard

A spreadsheet puzzle shows a row of digits and a target value. The player may put +, -, or * between any two neighboring digits, or nothing, which joins the digits into a longer number. Normal math rules apply: * is done before + and -.

A number with more than one digit can't start with 0 (05 is not allowed, but 0 alone is fine).

Write formulasForTarget(digits, target) that returns every formula whose value equals target, sorted by plain string comparison (so * comes before +, which comes before -, which comes before digits). Return [] if there is none.

Example 1

Input: digits = "123", target = 6
Output: ["1*2*3","1+2+3"]

1*2*3 = 6 and 1+2+3 = 6. * sorts before +.

Example 2

Input: digits = "232", target = 8
Output: ["2*3+2","2+3*2"]

Multiplication happens first: 2*3+2 = 8 and 2+3*2 = 8.

Constraints

  • 1 <= digits.length <= 13
  • digits only contains 0-9.
  • -10^8 <= target <= 10^8
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

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