Solve the Equation

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'.
SOLUTION:
class Solution:
    def parse(self, s):
        vals = [0, 0]
        chunk = ""
        sign = 1
        for c in s:
            if c == "+" or c == "-" or c == "s":
                if len(chunk) > 0:
                    if chunk[-1] == "x":
                        coefficient = chunk[:-1]
                        if not coefficient:
                            coefficient = "1"
                        vals[0] += sign * int(coefficient)
                    else:
                        vals[1] += sign * int(chunk)
                    chunk = ""
                if c == "+":
                    sign = 1
                elif c == "-":
                    sign = -1
            else:
                chunk += c
        return vals
    
    def solveEquation(self, equation: str) -> str:
        l, r = equation.split("=")
        lvals = self.parse(l + "s")
        rvals = self.parse(r + "s")
        numer = rvals[1] - lvals[1]
        denom = lvals[0] - rvals[0]
        if denom != 0:
            return "x={}".format(numer // denom)
        if numer != 0:
            return "No solution"
        return "Infinite solutions"

Comments

Popular posts from this blog

Encrypt and Decrypt Strings

Degree of an Array

Minimum Sum of Four Digit Number After Splitting Digits