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"
Difficulty
and has an acceptance rate of about 46% (100k+ submissions).
Typical patterns to solve this problem:
- Math
- Simulation
- String
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
Other Solutions
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 |
Similar Problems
- problem 592: Fraction Addition and Subtraction
- problem 2232: Minimize Result by Adding Parentheses to Expression
Solved On The Same Day
- problem 898: Bitwise ORs of Subarrays
- problem 915: Partition Array into Disjoint Intervals
- problem 947: Most Stones Removed with Same Row or Column
- problem 974: Subarray Sums Divisible by K
- problem 978: Longest Turbulent Subarray
- problem 1508: Range Sum of Sorted Subarray Sums
Extra
- 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