You get a string num made only of digits and an integer target. Between any two neighbouring digits you may put +, -, *, or nothing (which joins them into a longer number). The digits stay in order.
Return every expression built this way whose value is target, in any order. Normal precedence applies: * is done before + and -. No number in an expression may have a leading zero, so 0 is allowed but 05 is not.
Example 1
Input: num = "105", target = 5 Output: ["1*0+5","10-5"] Why: 1 × 0 + 5 = 5 and 10 − 5 = 5; "1+05" is not allowed
2 more examples and the constraints
Example 2
Input: num = "234", target = 14 Output: ["2+3*4"] Why: 3 × 4 is done first, then 2 is added
Example 3
Input: num = "7", target = 3 Output: [] Why: the only expression is 7
Constraints
- 1 ≤ num.length ≤ 10
- num contains only the digits 0 to 9
- −2³¹ ≤ target ≤ 2³¹ − 1
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Build every string, then evaluate itO(n · 4ⁿ)
- Backtrack with value and last termO(4ⁿ)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10 digits | Verdict |
|---|---|---|---|
| Build every string, then evaluate it | O(n · 4ⁿ) | Correct, but parses every string again | |
| Backtrack with value and last term | O(4ⁿ) | Best; the value is ready at the end |
n = length of num, at most 10. 4⁹ is 262,144 expressions.
Edge cases to test
- Leading zeros.
0is an operand,05is not: "05" with target 5 gives only0+5. - Zeros everywhere. "000000" with target 0 matches all 3⁵ = 243 operator choices.
- Big operands. "9999999999" is past 32 bits; with target 1,409,865,409 (its value modulo 2³²) a 32-bit version wrongly finds a match.
- Single digit. "7" can only be 7, so it matches target 7 and nothing else.
- Negative targets. Reachable with
-, but a leading minus sign is never allowed.
Common mistakes
- Handling
*by multiplying the whole running value instead of the last term. - Allowing operands such as
05, or forbidding the operand0itself. - Using 32-bit ints for operands and the running value.
How to talk through it
- 1Clarify. Can digits join into longer numbers? Are leading zeros allowed? Any output order?
- 2Count the space. Each of the n − 1 gaps has four choices, so up to 4ⁿ⁻¹ expressions: n ≤ 10 makes trying them all fine.
- 3Start simple. Build every string and evaluate it at the end; it works but re-parses everything.
- 4Carry the value. Track value and last term; for
*use value − last + last × x. - 5Test out loud. Run "105" for the zero rule, "234" for precedence, and a 10-digit string for overflow.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?