Solve the Equation — LeetCode 640 Python Solution
- Problem
- #640
- Pattern
- Math and Number Theory
- Reading time
- 5 min
- Source
- leetcode.com
The problem
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.
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
| Measure | Complexity |
|---|---|
| Time | O(n) or O(1) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 640. Solve the Equation is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 640. Solve the Equation?
- LeetCode 640. Solve the Equation is rated Medium on LeetCode.
- What topics does LeetCode 640. Solve the Equation cover?
- LeetCode 640. Solve the Equation is tagged Math, String and Simulation on LeetCode.