LeetCode 0640. Solve the Equation Solution in Java, Python, Go & TypeScript | Explanation + Code

CoderIndeed
0
0640. Solve the Equation

Description

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. You should return "No solution" if there is no solution for the equation, or "Infinite solutions" if there are infinite solutions for the equation.

If there is exactly one solution for the equation, we ensure that the value of 'x' is an integer.

 

Example 1:

Input: equation = "x+5-3+x=6+x-2"
Output: "x=2"

Example 2:

Input: equation = "x=x"
Output: "Infinite solutions"

Example 3:

Input: equation = "2x=x"
Output: "x=0"

 

Constraints:

  • 3 <= equation.length <= 1000
  • equation has exactly one '='.
  • equation consists of integers with an absolute value in the range [0, 100] without any leading zeros, and the variable 'x'.
  • The input is generated that if there is a single solution, it will be an integer.

Solutions

Solution 1: Mathematics

We split the equation by the equal sign "=" into left and right expressions, and compute the coefficient of "x" (denoted x_i) and the constant value (denoted y_i) for each side.

The equation is then transformed into: x_1 × x + y_1 = x_2 × x + y_2.

  • When x_1 = x_2: if y_1 ≠ y_2, there is no solution; if y_1 = y_2, there are infinite solutions.
  • When x_1 ≠ x_2: there is a unique solution x = y_2 - y_1x_1 - x_2.

Similar problems:

PythonJavaGoTypeScript
class Solution: def solveEquation(self, equation: str) -> str: def f(s): x = y = 0 if s[0] != '-': s = '+' + s i, n = 0, len(s) while i < n: sign = 1 if s[i] == '+' else -1 i += 1 j = i while j < n and s[j] not in '+-': j += 1 v = s[i:j] if v[-1] == 'x': x += sign * (int(v[:-1]) if len(v) > 1 else 1) else: y += sign * int(v) i = j return x, y a, b = equation.split('=') x1, y1 = f(a) x2, y2 = f(b) if x1 == x2: return 'Infinite solutions' if y1 == y2 else 'No solution' return f'x={(y2 - y1) // (x1 - x2)}'(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !