VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-all-possible-expressions-that-evaluate-to-a-target/

⇱ All possible expressions that evaluate to a target - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

All possible expressions that evaluate to a target

Last Updated : 30 Sep, 2025

Given a string digits containing only digits (0-9) and an integer target, find all possible expressions that evaluate to the target value using the binary operators +, -, and *. If no such expression is possible, return an empty list.

Input : digits = "124", target = 9
Output : [“1+2*4”]
Explanation: The valid expressions that evaluate to 9 are (1 + 2 * 4).

Input : digits = “125”, target = 7
Output : [“1*2+5”, “12-5”]
Explanation: The two valid expressions that evaluate to 7 are (1 * 2 + 5) and (12 - 5). 

[Approach] Using Recursion

We can generate all expressions by inserting the operators +, -, and * between the digits recursively. At each recursion step:

  • Maintain the current expression, the evaluated value so far, and the last operand.
  • For + or -, simply add or subtract the current number and update the last operand.
  • For *, adjust the evaluated value to respect precedence: subtract the last operand from the current value and add the product of the last operand and current number; then update the last operand.
  • Recursively continue until all digits are used, and collect expressions whose evaluated value equals the target.

Multiplication Handling:

  • Multiplication has higher precedence than addition or subtraction.
  • Suppose the current expression is 1 + 2 (evaluated value = 3, last operand = 2) and we want to add *5.
  • Instead of evaluating left-to-right, we remove the last operand from the current value (3 - 2 = 1) and add the product of the last operand and the new number (1 + 2*5 = 11).
  • Update the last operand to the new product (2*5 = 10).

This adjustment ensures that 1 + 2*5 is evaluated correctly as 1 + (2*5) rather than (1 + 2)*5.


Output
1+2*4 

Time Complexity: O(4n), because at each of the n-1 positions between digits we can insert one of three operators +, -, * or choose no operator (concatenate digits), generating all possible expressions.
Auxiliary Space: O(n), for the recursion stack and the current expression being built;

Comment
Article Tags:
Article Tags: