Solve the Equation — LeetCode 640 Python Solution

MediumMathStringSimulation
Problem
#640
Reading time
5 min

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

Python
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

MeasureComplexity
TimeO(n) or O(1)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview