640. Solve the Equation
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method Explanation
The problem requires us to solve a simple linear equation in one variable, x. The equation is provided as a string. A general linear equation can be written as ax + b = cx + d. Our goal is to find the value of x.
Solution
Solve the Equation in Python
class Solution:
def solveEquation(self, equation: str) -> str:
def parse(s: str) -> tuple[int, int]:
"""Helper to parse one side of the equation.
Returns (x_coefficient, constant_value)."""
x_coeff = 0
const_val = 0
i = 0
n = len(s)
while i < n:
sign = 1
if s[i] == '+':
i += 1
elif s[i] == '-':
sign = -1
i += 1
# Parse a term
j = i
while j < n and s[j].isdigit():
j += 1
num_str = s[i:j]
if j < n and s[j] == 'x': # Term with 'x'
if not num_str: # 'x' means '1x'
x_coeff += sign * 1
else:
x_coeff += sign * int(num_str)
i = j + 1
else: # Constant term
if num_str:
const_val += sign * int(num_str)
i = j
return (x_coeff, const_val)
lhs_str, rhs_str = equation.split('=')
x_coeff_l, const_val_l = parse(lhs_str)
x_coeff_r, const_val_r = parse(rhs_str)
# Rearrange to: (x_coeff_l - x_coeff_r)x = const_val_r - const_val_l
final_x_coeff = x_coeff_l - x_coeff_r
final_const_val = const_val_r - const_val_l
if final_x_coeff == 0:
if final_const_val == 0:
return "Infinite solutions"
else:
return "No solution"
else:
return f"x={final_const_val // final_x_coeff}"
Solve the Equation in Java
class Solution {
// Helper function to parse an expression string (one side of the equation).
// It returns an array: {coefficient of x, constant value}.
private int[] parse(String s) {
int xCoeff = 0;
int constVal = 0;
int i = 0;
int n = s.length();
while (i < n) {
int sign = 1;
if (s.charAt(i) == '+') {
i++;
} else if (s.charAt(i) == '-') {
sign = -1;
i++;
}
// Now parse a term.
int j = i;
while (j < n && Character.isDigit(s.charAt(j))) {
j++;
}
String numStr = s.substring(i, j);
if (j < n && s.charAt(j) == 'x') { // Term with 'x'
if (numStr.isEmpty()) { // 'x' means '1x'
xCoeff += sign * 1;
} else {
xCoeff += sign * Integer.parseInt(numStr);
}
i = j + 1;
} else { // Constant term
if (!numStr.isEmpty()) {
constVal += sign * Integer.parseInt(numStr);
}
i = j;
}
}
return new int[]{xCoeff, constVal};
}
public String solveEquation(String equation) {
int eqPos = equation.indexOf('=');
String lhsStr = equation.substring(0, eqPos);
String rhsStr = equation.substring(eqPos + 1);
int[] lhs = parse(lhsStr);
int[] rhs = parse(rhsStr);
// equation becomes: lhs[0]x + lhs[1] = rhs[0]x + rhs[1]
// Rearranging: (lhs[0] - rhs[0])x = rhs[1] - lhs[1]
int finalXCoeff = lhs[0] - rhs[0];
int finalConstVal = rhs[1] - lhs[1];
if (finalXCoeff == 0) {
if (finalConstVal == 0) {
return "Infinite solutions";
} else {
return "No solution";
}
} else {
return "x=" + (finalConstVal / finalXCoeff);
}
}
}
Solve the Equation in C++
class Solution {
public:
// Helper function to parse an expression string (one side of the equation).
// It returns a pair: {coefficient of x, constant value}.
pair<int, int> parse(string s) {
int x_coeff = 0;
int const_val = 0;
int i = 0;
int n = s.length();
while (i < n) {
int sign = 1;
if (s[i] == '+') {
i++;
} else if (s[i] == '-') {
sign = -1;
i++;
}
// Now parse a term. A term is a number or a number followed by 'x'.
int j = i;
while (j < n && isdigit(s[j])) {
j++;
}
string num_str = s.substr(i, j - i);
if (j < n && s[j] == 'x') { // This is a term with 'x'.
if (num_str.empty()) { // 'x' or '-x' or '+x'
x_coeff += sign * 1;
} else {
x_coeff += sign * stoi(num_str);
}
i = j + 1;
} else { // This is a constant term.
if (!num_str.empty()) {
const_val += sign * stoi(num_str);
}
i = j;
}
}
return {x_coeff, const_val};
}
string solveEquation(string equation) {
size_t eq_pos = equation.find('=');
string lhs_str = equation.substr(0, eq_pos);
string rhs_str = equation.substr(eq_pos + 1);
pair<int, int> lhs = parse(lhs_str);
pair<int, int> rhs = parse(rhs_str);
// equation becomes: (lhs.first)x + lhs.second = (rhs.first)x + rhs.second
// Rearranging: (lhs.first - rhs.first)x = rhs.second - lhs.second
int x_coeff_final = lhs.first - rhs.first;
int const_val_final = rhs.second - lhs.second;
if (x_coeff_final == 0) {
if (const_val_final == 0) {
return "Infinite solutions";
} else {
return "No solution";
}
} else {
return "x=" + to_string(const_val_final / x_coeff_final);
}
}
};
Solve the Equation in TypeScript
function solveEquation(equation: string): string {
// Helper function to parse an expression string (one side of the equation).
// It returns a pair: [coefficient of x, constant value].
const parse = (s: string): [number, number] => {
let xCoeff = 0;
let constVal = 0;
let i = 0;
const n = s.length;
while (i < n) {
let sign = 1;
if (s[i] === '+') {
i++;
} else if (s[i] === '-') {
sign = -1;
i++;
}
// Now parse a term.
let j = i;
while (j < n && s[j] >= '0' && s[j] <= '9') {
j++;
}
const numStr = s.substring(i, j);
if (j < n && s[j] === 'x') { // Term with 'x'
if (numStr === '') { // 'x' means '1x'
xCoeff += sign * 1;
} else {
xCoeff += sign * parseInt(numStr);
}
i = j + 1;
} else { // Constant term
if (numStr !== '') {
constVal += sign * parseInt(numStr);
}
i = j;
}
}
return [xCoeff, constVal];
};
const parts = equation.split('=');
const lhsStr = parts[0];
const rhsStr = parts[1];
const [lhsX, lhsConst] = parse(lhsStr);
const [rhsX, rhsConst] = parse(rhsStr);
// equation becomes: lhsX*x + lhsConst = rhsX*x + rhsConst
// Rearranging: (lhsX - rhsX)x = rhsConst - lhsConst
const finalXCoeff = lhsX - rhsX;
const finalConstVal = rhsConst - lhsConst;
if (finalXCoeff === 0) {
if (finalConstVal === 0) {
return "Infinite solutions";
} else {
return "No solution";
}
} else {
return `x=${finalConstVal / finalXCoeff}`;
}
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.