Leetcode•Nov 11, 2026
Solve the Equation
Hazrat Ali
Leetcode
Solve a given equation and return the value of 'x' in the form of a string "x=#value". The equation contains only '+', '-' operation, the variable 'x' and its coefficient. You should return "No solution" if there is no solution for the equation, or "Infinite solutions" if there are infinite solutions for the equation.
If there is exactly one solution for the equation, we ensure that the value of 'x' is an integer.
Example 1:
Input: equation = "x+5-3+x=6+x-2" Output: "x=2"
Example 2:
Input: equation = "x=x" Output: "Infinite solutions"
Example 3:
Input: equation = "2x=x" Output: "x=0"
Solution
var solveEquation = function(equation) {
const [left, right] = equation.split('=');
function evaluate(expression) {
let x = 0;
let num = 0;
expression = '+' + expression;
const tokens = expression.match(/[+-][^+-]+/g);
for (const token of tokens) {
const sign = token[0] === '+' ? 1 : -1;
const value = token.slice(1);
if (value.includes('x')) {
const coefficient = value === 'x'
? 1
: Number(value.slice(0, -1));
x += sign * coefficient;
} else {
num += sign * Number(value);
}
}
return [x, num];
}
const [leftX, leftNum] = evaluate(left);
const [rightX, rightNum] = evaluate(right);
const coefficient = leftX - rightX;
const constant = rightNum - leftNum;
if (coefficient === 0) {
return constant === 0
? "Infinite solutions"
: "No solution";
}
return `x=${constant / coefficient}`;
};