Open In App

Print all possible expressions that evaluate to a target

Last Updated : 02 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

The problem is solved by placing binary operators (+, -, *) between digits and checking if the resulting expression equals the target.

The recursive approach tracks:

  • The current expression
  • Evaluated value so far
  • Last operand (for correct * evaluation)

The last operand is needed to adjust precedence when multiplying. 

Suppose the input is "125" and the current expression is "1+2":

  • position = 2, current value = 3, last = 2

To handle multiplication (e.g., "1+2*5"), we adjust for operator precedence:

  • Subtract the last value and add last * 5
  • current value = 3 - 2 + (2 * 5) = 11
  • Update last = 10

This ensures the expression is evaluated correctly as "1 + (2 * 5)".

C++
// C++ Program to generate all expressions from a string of digits
// that evaluate to a target value

#include <iostream>
#include <vector>
#include <string>
using namespace std;

// Helper function to build expressions
void buildExpr(vector<string>& res, string expr, string digits,
               int target, int idx, long long eval, long long last) {

    if (idx == digits.length()) {
        if (eval == target)
            res.push_back(expr);
        return;
    }

    for (int i = idx; i < digits.length(); i++) {
        
        // Skip numbers with leading zero
        if (i != idx && digits[idx] == '0') break;

        string part = digits.substr(idx, i - idx + 1);
        long long num = stoll(part);

        if (idx == 0) {
            buildExpr(res, part, digits, target, i + 1, num, num);
        } else {
            buildExpr(res, expr + "+" + part, digits, target, i + 1, eval + num, num);
            buildExpr(res, expr + "-" + part, digits, target, i + 1, eval - num, -num);
            buildExpr(res, expr + "*" + part, digits, target, i + 1,
                      eval - last + last * num, last * num);
        }
    }
}

// Function to return expressions evaluating to the target
vector<string> findExpr(string digits, int target) {
    vector<string> res;
    buildExpr(res, "", digits, target, 0, 0, 0);
    return res;
}

// Function to print results
void showExpr(const vector<string>& res) {
    if (res.empty()) {
        cout << "[]" << endl;
    } else {
        for (const string& e : res)
            cout << e << " ";
        cout << endl;
    }
}

int main() {
    string digits = "124";
    int target = 9;
    vector<string> res = findExpr(digits, target);
    showExpr(res);


    return 0;
}
Java
// Java Program to generate all expressions from a string of digits
// that evaluate to a target value

import java.util.ArrayList;

public class GfG {

    // Helper function to build expressions
    static void buildExpr(ArrayList<String> res, String expr, String digits,
                          int target, int idx, long eval, long last) {
        if (idx == digits.length()) {
            if (eval == target)
                res.add(expr);
            return;
        }

        for (int i = idx; i < digits.length(); i++) {
            if (i != idx && digits.charAt(idx) == '0') break;

            String part = digits.substring(idx, i + 1);
            long num = Long.parseLong(part);

            if (idx == 0) {
                buildExpr(res, part, digits, target, i + 1, num, num);
            } else {
                buildExpr(res, expr + "+" + part, digits, target, i + 1, eval + num, num);
                buildExpr(res, expr + "-" + part, digits, target, i + 1, eval - num, -num);
                buildExpr(res, expr + "*" + part, digits, target, i + 1,
                          eval - last + last * num, last * num);
            }
        }
    }

    // Function to return expressions evaluating to the target
    static ArrayList<String> findExpr(String digits, int target) {
        ArrayList<String> res = new ArrayList<>();
        buildExpr(res, "", digits, target, 0, 0, 0);
        return res;
    }

    // Function to print results
    static void showExpr(ArrayList<String> res) {
        if (res.isEmpty()) {
            System.out.println("[]");
        } else {
            for (String e : res)
                System.out.print(e + " ");
            System.out.println();
        }
    }

    public static void main(String[] args) {
        String digits = "124";
        int target = 9;
        ArrayList<String> res = findExpr(digits, target);
        showExpr(res);

       
    }
}
Python
# Python Program to generate all expressions from a string of digits
# that evaluate to a target value

# Function to build expressions
def buildExpr(res, expr, digits, target, idx, evalVal, last):
    
    if idx == len(digits):
        if evalVal == target:
            res.append(expr)
        return

    for i in range(idx, len(digits)):

        # Skip numbers with leading zero
        if i != idx and digits[idx] == '0':
            break

        part = digits[idx:i+1]
        num = int(part)

        if idx == 0:
            buildExpr(res, part, digits, target, i + 1, num, num)
        else:
            buildExpr(res, expr + "+" + part, digits, target, i + 1, evalVal + num, num)
            buildExpr(res, expr + "-" + part, digits, target, i + 1, evalVal - num, -num)
            buildExpr(res, expr + "*" + part, digits, target, i + 1, evalVal - last + last * num, last * num)

# Function to return expressions evaluating to target
def findExpr(digits, target):
    res = []
    buildExpr(res, "", digits, target, 0, 0, 0)
    return res

# Function to print result
def showExpr(res):
    if not res:
        print("[]")
    else:
        print(" ".join(res))

if __name__ == "__main__":
    digits = "124"
    target = 9
    res = findExpr(digits, target)
    showExpr(res)
C#
// C# Program to generate all expressions from a string of digits
// that evaluate to a target value
using System;
using System.Collections.Generic;

class GfG {

    // Function to build expressions
    static void buildExpr(List<string> res, string expr, string digits, int target,
                                int idx, long eval, long last) {
        if (idx == digits.Length) {
            if (eval == target)
                res.Add(expr);
            return;
        }

        for (int i = idx; i < digits.Length; i++) {

            // Skip numbers with leading zero
            if (i != idx && digits[idx] == '0') break;

            string part = digits.Substring(idx, i - idx + 1);
            long num = long.Parse(part);

            if (idx == 0) {
                buildExpr(res, part, digits, target, i + 1, num, num);
            } else {
                buildExpr(res, expr + "+" + part, digits, target, i + 1, eval + num, num);
                buildExpr(res, expr + "-" + part, digits, target, i + 1, eval - num, -num);
                buildExpr(res, expr + "*" + part, digits, target, i + 1, eval - last + last * num, last * num);
            }
        }
    }

    // Function to return expressions
    static List<string> findExpr(string digits, int target) {
        List<string> res = new List<string>();
        buildExpr(res, "", digits, target, 0, 0, 0);
        return res;
    }

    // Function to print results
    static void showExpr(List<string> res) {
        if (res.Count == 0) {
            Console.WriteLine("[]");
        } else {
            foreach (string s in res)
                Console.Write(s + " ");
            Console.WriteLine();
        }
    }

    static void Main(string[] args) {
        string digits = "124";
        int target = 9;
        List<string> res = findExpr(digits, target);
        showExpr(res);

    }
}
JavaScript
// JavaScript Program to generate all expressions from a string of digits
// that evaluate to a target value

// Function to build expressions
function buildExpr(res, expr, digits, target, idx, evalVal, last) {

    if (idx === digits.length) {
        if (evalVal === target) res.push(expr);
        return;
    }

    for (let i = idx; i < digits.length; i++) {

        // Skip numbers with leading zero
        if (i !== idx && digits[idx] === '0') break;

        let part = digits.substring(idx, i + 1);
        let num = parseInt(part);

        if (idx === 0) {
            buildExpr(res, part, digits, target, i + 1, num, num);
        } else {
            buildExpr(res, expr + "+" + part, digits, target, i + 1, evalVal + num, num);
            buildExpr(res, expr + "-" + part, digits, target, i + 1, evalVal - num, -num);
            buildExpr(res, expr + "*" + part, digits, target, i + 1, evalVal - last + last * num, last * num);
        }
    }
}

// Function to return expressions
function findExpr(digits, target) {
    let res = [];
    buildExpr(res, "", digits, target, 0, 0, 0);
    return res;
}

// Function to print results
function showExpr(res) {
    if (res.length === 0) {
        console.log("[]");
    } else {
        console.log(res.join(" "));
    }
}

// Driver code
let digits = "124";
let target = 9;
let res = findExpr(digits, target);
showExpr(res);

Output
1+2*4 

Time Complexity: O(4n ), where n is length of expression
Auxiliary Space: O(n) 
 


Next Article
Article Tags :
Practice Tags :

Similar Reads