class Solution:
def solveEquation(self, equation: str) -> str:
def parse(expr):
coef, const, i, sign = 0, 0, 0, 1
n = len(expr)
while i < n:
if expr[i] == '+':
sign = 1
i += 1
elif expr[i] == '-':
sign = -1
i += 1
else:
j = i
while j < n and expr[j].isdigit():
j += 1
num = int(expr[i:j]) if j > i else 1
if j < n and expr[j] == 'x':
coef += sign * num
j += 1
else:
const += sign * num
i = j
return coef, const
left, right = equation.split('=')
lcoef, lconst = parse(left)
rcoef, rconst = parse(right)
coef = lcoef - rcoef
const = rconst - lconst
if coef == 0:
if const == 0:
return "Infinite solutions"
else:
return "No solution"
else:
return f"x={const // coef}"
class Solution {
public:
string solveEquation(string equation) {
auto parse = [](const string& expr) {
int coef = 0, constant = 0, sign = 1, i = 0, n = expr.size();
while (i < n) {
if (expr[i] == '+') {
sign = 1;
i++;
} else if (expr[i] == '-') {
sign = -1;
i++;
} else {
int j = i, num = 0, hasNum = 0;
while (j < n && isdigit(expr[j])) {
num = num * 10 + (expr[j] - '0');
j++;
hasNum = 1;
}
if (j < n && expr[j] == 'x') {
coef += sign * (hasNum ? num : 1);
j++;
} else {
constant += sign * (hasNum ? num : 0);
}
i = j;
}
}
return make_pair(coef, constant);
};
int eq = equation.find('=');
auto left = parse(equation.substr(0, eq));
auto right = parse(equation.substr(eq + 1));
int coef = left.first - right.first;
int constant = right.second - left.second;
if (coef == 0) {
if (constant == 0) return "Infinite solutions";
else return "No solution";
}
return "x=" + to_string(constant / coef);
}
};
class Solution {
public String solveEquation(String equation) {
int[] left = parse(equation.split("=")[0]);
int[] right = parse(equation.split("=")[1]);
int coef = left[0] - right[0];
int constVal = right[1] - left[1];
if (coef == 0) {
if (constVal == 0) return "Infinite solutions";
else return "No solution";
}
return "x=" + (constVal / coef);
}
private int[] parse(String expr) {
int coef = 0, constant = 0, sign = 1, i = 0, n = expr.length();
while (i < n) {
if (expr.charAt(i) == '+') {
sign = 1;
i++;
} else if (expr.charAt(i) == '-') {
sign = -1;
i++;
} else {
int j = i, num = 0, hasNum = 0;
while (j < n && Character.isDigit(expr.charAt(j))) {
num = num * 10 + (expr.charAt(j) - '0');
j++;
hasNum = 1;
}
if (j < n && expr.charAt(j) == 'x') {
coef += sign * (hasNum == 1 ? num : 1);
j++;
} else {
constant += sign * (hasNum == 1 ? num : 0);
}
i = j;
}
}
return new int[] {coef, constant};
}
}
var solveEquation = function(equation) {
function parse(expr) {
let coef = 0, constant = 0, sign = 1, i = 0, n = expr.length;
while (i < n) {
if (expr[i] === '+') {
sign = 1;
i++;
} else if (expr[i] === '-') {
sign = -1;
i++;
} else {
let j = i, num = 0, hasNum = false;
while (j < n && /\d/.test(expr[j])) {
num = num * 10 + parseInt(expr[j]);
j++;
hasNum = true;
}
if (j < n && expr[j] === 'x') {
coef += sign * (hasNum ? num : 1);
j++;
} else {
constant += sign * (hasNum ? num : 0);
}
i = j;
}
}
return [coef, constant];
}
let [left, right] = equation.split('=');
let [lcoef, lconst] = parse(left);
let [rcoef, rconst] = parse(right);
let coef = lcoef - rcoef;
let constant = rconst - lconst;
if (coef === 0) {
if (constant === 0) return "Infinite solutions";
else return "No solution";
}
return "x=" + (constant / coef);
};
You are given a string equation
representing a linear equation in one variable x
. The equation contains integer coefficients, the variable x
, plus and minus signs, and an equals sign (=
). Your task is to find the value of x
that satisfies the equation.
The equation is always valid and formatted as left side = right side
. You must return:
"x=#value"
if there is a unique solution for x
"Infinite solutions"
if there are infinite solutions (the two sides are always equal)"No solution"
if there is no possible value for x
that satisfies the equation2x
, -x
, +3
, etc. The coefficients and constants are integers. There is always exactly one variable x
in the equation.
At first glance, this problem looks like a typical algebraic manipulation. But as a programmer, we need to parse and interpret the string to extract coefficients and constants.
A brute-force approach might try to evaluate values for x
until the equation balances, but this is inefficient and unnecessary. Instead, we can "collect like terms" as we would on paper: move all terms involving x
to one side and all constants to the other, then solve for x
.
The main challenge is correctly parsing the string, handling signs, and distinguishing between coefficients of x
and constants. We need to:
x
x
using simple algebraLet's break down the steps to solve the equation programmatically:
=
sign to divide the equation into left and right parts.
x
x
.
x
terms to one side (subtract right from left) and all constants to the other (subtract left from right).
x
:
x
is zero:"Infinite solutions"
"No solution"
"x=#value"
where #value
is the integer result of dividing the constants by the coefficient.We use simple arithmetic and string parsing for this, and no advanced data structures are required.
Let's use the example "x+5-3+x=6+x-2"
.
"x+5-3+x"
, right: "6+x-2"
x
: coefficient +1+5
: constant +5-3
: constant -3+x
: coefficient +16
: constant +6+x
: coefficient +1-2
: constant -2x
terms to one side: 2 - 1 = 1x = 2
"x=2"
Brute-force approach: Trying every possible integer value for x
is extremely inefficient, potentially O(N) for N possible values.
Optimized parsing approach: We scan each character of the equation once to parse coefficients and constants. Thus:
The key to solving the "Solve the Equation" problem is to treat the equation like an algebraic expression: parse both sides, collect like terms, and solve for x
. By methodically extracting coefficients and constants with a string parser, we avoid brute-force and achieve an elegant O(N) solution. This approach combines basic string processing with algebraic manipulation, making it efficient and reliable.