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.
C++
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void buildExpr(vector<string>& res, string expr, string digits,
int target, int idx, int eval, int 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);
int 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 valid expressions
vector<string> findExpr(string digits, int target) {
vector<string> res;
buildExpr(res, "", digits, target, 0, 0, 0);
return res;
}
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
import java.util.ArrayList;
class GFG {
static void buildExpr(ArrayList<String> res, String expr, String digits,
int target, int idx, int eval, int 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.charAt(idx) == '0') break;
String part = digits.substring(idx, i + 1);
int num = Integer.parseInt(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 valid expressions
static ArrayList<String> findExpr(String digits, int target) {
ArrayList<String> res = new ArrayList<>();
buildExpr(res, "", digits, target, 0, 0, 0);
return res;
}
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
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 valid expressions
def findExpr(digits, target):
res = []
buildExpr(res, "", digits, target, 0, 0, 0)
return res
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#
using System;
using System.Collections.Generic;
class GfG {
static void buildExpr(List<string> res, string expr, string digits, int target,
int idx, int eval, int 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);
int num = int.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 valid expressions
static List<string> findExpr(string digits, int target) {
List<string> res = new List<string>();
buildExpr(res, "", digits, target, 0, 0, 0);
return res;
}
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
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 valid expressions
function findExpr(digits, target) {
let res = [];
buildExpr(res, "", digits, target, 0, 0, 0);
return res;
}
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);
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;
Explore
DSA Fundamentals
Data Structures
Algorithms
Advanced
Interview Preparation
Practice Problem