Leetcode #640: Solve the Equation
In this guide, we solve Leetcode #640 Solve the Equation in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Math, String, Simulation
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
Input: equation = "x+5-3+x=6+x-2"
Output: "x=2"
Python Solution
def solveEquation(equation: str) -> str:
def parse(expr: str):
expr = expr.replace('-', '+-')
parts = expr.split('+')
coef = 0
const = 0
for p in parts:
if not p:
continue
if 'x' in p:
val = p.replace('x', '')
if val == '' or val == '+':
coef += 1
elif val == '-':
coef -= 1
else:
coef += int(val)
else:
const += int(p)
return coef, const
left, right = equation.split('=')
coef_l, const_l = parse(left)
coef_r, const_r = parse(right)
coef = coef_l - coef_r
const = const_r - const_l
if coef == 0:
return 'Infinite solutions' if const == 0 else 'No solution'
return f"x={const // coef}"
Complexity
The time complexity is O(n) or O(1). The space complexity is O(1).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.