Problem statement

https://leetcode.com/problems/solve-the-equation/

Solution

What we need to do in this problem is to parse our string, first checking the left and the right parts, and then parsing each part, splitting by + and - and returning numbers a and b, where we have term ax + b. For each term we need to check if it is number (then it ends not with x), if it is ends with x or it is just x.

Complexity

Time and space complexity is O(n), where n is length of original string.

Code

class Solution:
    def solveEquation(self, equation):
        def ProcessPart(s, a=0, b=0):
            if s[0] not in "+-": s = "+" + s
            terms = re.split("[+-]+", s)[1:]
            signs= [int(q=="+")*2-1 for q in s if q in "+-"]
            for x, y in zip(terms, signs):
                if x == "x": a += y
                elif x[-1] == "x": a += y*int(x[:-1])
                else: b += y*int(x)
            return (a, b)
        
        left, right = equation.split("=")
        a1, b1 = ProcessPart(left)
        a2, b2 = ProcessPart(right)
              
        if a1 == a2 and b1 == b2: return "Infinite solutions"
        if a1 == a2 and b1 != b2: return "No solution"
        return "x=" + str((b2-b1)//(a1-a2))