Problem 640

Abstract / Summary

Find values of x that make a given linear equation true by parsing and simplifying both sides of the equation.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0640.py

class Solution:
    def solveEquation(self, equation: str) -> str:
        left, right = equation.split("=")

        def compute(formula, value): # value should be a string
            # if value == "7": "3+2x" => "3+2*7" => eval
            #                  "3+x"  => "3+*7"  => "3+7" => eval
            formula = formula.replace("x", "*" + value)
            formula = formula.replace("+*", "+")
            formula = formula.replace("-*", "-")
            if formula[0] == "*":
                formula = formula[1 :]

            return eval(formula)

        solution = None
        for i in range(1000):
            for sign in [ -1, +1 ]:
                n = str(i * sign)
                l = compute(left,  n)
                r = compute(right, n)
                if l == r:
                    if solution is not None:
                        return "Infinite solutions"

                    solution = "x=" + n

                # zero has no sign
                if i == 0:
                    break

        return solution if solution is not None else "No solution"
32 lines | 1113 bytes | submitted May 9, 2024 | GitHub   17% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 46% (100k+ submissions).

Typical patterns to solve this problem:
  • Math
  • Simulation
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method solveEquation that receives a linear equation expressed as a string, such as "2x+3=7", and returns a textual description of the solution. The method works by separating the equation into left-hand and right-hand expressions, then systematically testing integer values for the variable x until a match is found, an infinite set of solutions is detected, or the search space is exhausted.

Key Steps

The first operation splits the input at the equality sign, producing two independent formulas that can be evaluated separately.

left, right = equation.split("=")

A nested helper function compute is defined to evaluate a formula for a specific integer value supplied as a string. The function replaces occurrences of the variable x with a multiplication by the supplied value, cleans up any stray operators that may arise from the replacement, and finally uses Python’s eval to obtain the numeric result.

def compute(formula, value):
    formula = formula.replace("x", "*" + value)
    formula = formula.replace("+*", "+")
    formula = formula.replace("-*", "-")
    if formula[0] == "*":
        formula = formula[1:]
    return eval(formula)

The core solving loop iterates over a bounded range of integer magnitudes (0 through 999). For each magnitude the loop tests both the positive and negative sign, constructing the candidate value as a string. The helper compute is invoked for both sides of the equation, and the results are compared.

solution = None
for i in range(1000):
    for sign in [-1, +1]:
        n = str(i * sign)
        l = compute(left, n)
        r = compute(right, n)
        if l == r:
            if solution is not None:
                return "Infinite solutions"
            solution = "x=" + n
        if i == 0:
            break

If a matching value is discovered and no previous solution has been recorded, the method stores the textual representation "x=" concatenated with the found integer. Encountering a second matching value triggers an immediate return of "Infinite solutions". After the search completes, the method returns the stored solution if one exists; otherwise it returns "No solution".

return solution if solution is not None else "No solution"

Edge Cases Handled

The algorithm explicitly treats the integer zero as a special case by breaking out of the inner sign loop when i equals zero. This prevents redundant evaluation of +0 and -0, ensuring that zero is considered only once. The replacement logic inside compute removes a leading asterisk that would otherwise produce a syntax error when the variable appears at the start of the expression (e.g., "x+5" becomes "*7+5" after substitution, and the leading asterisk is stripped). Additionally, the cleanup of "+*" and "-*" sequences guarantees that expressions such as "3+x" correctly transform into "3+7" rather than an invalid "3+*7". The detection of multiple valid integer solutions is handled by checking whether a solution has already been recorded; encountering a second match leads to the "Infinite solutions" response, covering cases where the equation reduces to an identity like "0=0" after substitution.

Performance Optimizations

The search space is limited to a fixed range of 1000 absolute values, which bounds the number of evaluations and prevents unbounded computation. By testing both signs within the same outer loop, the code avoids separate loops for positive and negative values, reducing overhead. The early break for the zero case eliminates unnecessary duplicate work for the sign iteration when i is zero. String replacement operations are performed in place without constructing additional intermediate data structures beyond the temporary strings needed for substitution, keeping the per-iteration cost low. The use of Python’s built-in eval leverages the interpreter’s optimized expression evaluation rather than implementing a custom arithmetic parser, providing a concise and efficient means of computing the numeric results of the transformed formulas.

written by openai gpt

ELI5 - Simplified Explanation

Imagine this code is like a game where a detective tries to find a secret number hidden behind the letter x. The computer has two sides of an equation and wants to make both sides balance out perfectly like a scale. To do this, the computer acts like a curious explorer and tries out lots of different numbers, starting from negative numbers and going all the way up to positive numbers.

For every number it picks, it swaps the x in the equation with that number to see if the left side matches the right side. If the sides balance, the computer knows it found the right answer. The computer keeps checking a whole bunch of numbers just in case there are multiple answers or if there is no answer at all. Once it finishes checking, it says whether it found a single secret number, if there are infinite numbers that work, or if it turns out that no number works at all.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 3 | μ = 3.46 | σ = 1.71

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Java C++ Python TS
WalkCCC Java C++ Python
leetcode.ca Java Python Go TS
LeetcodeHelp Java C++ Python
Progiez Java C++ Python
github black-shadows C++
charles-wangkai Java
everthis JS
gouthampradhan Java
JoshCrozier JS
linouk23 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
gouthampradhan Java
JoshCrozier JavaScript
linouk23 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
varunu28 Java
27 links | 15 authors | 8 languages

Similar Problems

2 similar problems

Solved On The Same Day

7 solutions   May 9, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality