Formatted question description: https://leetcode.ca/all/640.html

640. Solve the Equation (Medium)

Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.

If there is no solution for the equation, return "No solution".

If there are infinite solutions for the equation, return "Infinite solutions".

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

Example 1:

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

Example 2:

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

Example 3:

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

Example 4:

Input: "2x+3x-6x=x+2"
Output: "x=-1"

Example 5:

Input: "x=x+2"
Output: "No solution"

Companies:
Google, Uber

Related Topics:
Math

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/solve-the-equation/
// Time: O(N)
// Space: O(1)
class Solution {
private:
    int read(string &equation, int pos, bool &isNum, int &num) {
        if (equation[pos] == '=') ++pos;
        int sign = 1, N = equation.size();
        if (equation[pos] == '+' || equation[pos] == '-') {
            if (equation[pos] == '-') sign = -1;
            ++pos;
        }
        if (pos < N && equation[pos] == 'x') {
            num = 1;
        } else {
            num = 0;
            while (pos < N && isdigit(equation[pos])) {
                num = num * 10 + equation[pos++] - '0';
            }
        }
        isNum = true;
        if (pos < N && equation[pos] == 'x') {
            isNum = false;
            ++pos;
        }
        num *= sign;
        return pos;
    }
public:
    string solveEquation(string equation) {
        int i = 0, N = equation.size(), space = equation.find_first_of("=");
        int coef = 0, val = 0;
        while (i < N) {
            bool isNum;
            int num;
            i = read(equation, i, isNum, num);
            int sign = i <= space ? 1 : -1;
            if (isNum) val -= sign * num;
            else coef += sign * num;
        }
        if (coef) return "x=" + to_string(val / coef);
        return val ? "No solution" : "Infinite solutions";
    }
};

Java

  • class Solution {
        public String solveEquation(String equation) {
            equation = equation.replaceAll("-", "+-");
            if (equation.charAt(0) == '+')
                equation = equation.substring(1);
            equation = equation.replace("=+", "=");
            int equalIndex = equation.indexOf('=');
            String leftSide = equation.substring(0, equalIndex);
            String rightSide = equation.substring(equalIndex + 1);
            String[] leftArray = leftSide.split("\\+");
            String[] rightArray = rightSide.split("\\+");
            int xTerm = 0, constantTerm = 0;
            for (String leftTerm : leftArray) {
                if (leftTerm.contains("x")) {
                    if (leftTerm.equals("x"))
                        xTerm++;
                    else if (leftTerm.equals("-x"))
                        xTerm--;
                    else {
                        String coefficientStr = leftTerm.substring(0, leftTerm.indexOf('x'));
                        int coefficient = Integer.parseInt(coefficientStr);
                        xTerm += coefficient;
                    }
                } else
                    constantTerm -= Integer.parseInt(leftTerm);
            }
            for (String rightTerm : rightArray) {
                if (rightTerm.contains("x")) {
                    if (rightTerm.equals("x"))
                        xTerm--;
                    else if (rightTerm.equals("-x"))
                        xTerm++;
                    else {
                        String coefficientStr = rightTerm.substring(0, rightTerm.indexOf('x'));
                        int coefficient = Integer.parseInt(coefficientStr);
                        xTerm -= coefficient;
                    }
                } else
                    constantTerm += Integer.parseInt(rightTerm);
            }
            if (xTerm != 0) {
                int solution = constantTerm / xTerm;
                return "x=" + solution;
            } else if (constantTerm == 0)
                return "Infinite solutions";
            else
                return "No solution";
        }
    }
    
  • // OJ: https://leetcode.com/problems/solve-the-equation/
    // Time: O(N)
    // Space: O(1)
    class Solution {
    private:
        int read(string &equation, int pos, bool &isNum, int &num) {
            if (equation[pos] == '=') ++pos;
            int sign = 1, N = equation.size();
            if (equation[pos] == '+' || equation[pos] == '-') {
                if (equation[pos] == '-') sign = -1;
                ++pos;
            }
            if (pos < N && equation[pos] == 'x') {
                num = 1;
            } else {
                num = 0;
                while (pos < N && isdigit(equation[pos])) {
                    num = num * 10 + equation[pos++] - '0';
                }
            }
            isNum = true;
            if (pos < N && equation[pos] == 'x') {
                isNum = false;
                ++pos;
            }
            num *= sign;
            return pos;
        }
    public:
        string solveEquation(string equation) {
            int i = 0, N = equation.size(), space = equation.find_first_of("=");
            int coef = 0, val = 0;
            while (i < N) {
                bool isNum;
                int num;
                i = read(equation, i, isNum, num);
                int sign = i <= space ? 1 : -1;
                if (isNum) val -= sign * num;
                else coef += sign * num;
            }
            if (coef) return "x=" + to_string(val / coef);
            return val ? "No solution" : "Infinite solutions";
        }
    };
    
  • class Solution(object):
      def solveEquation(self, equation):
        """
        :type equation: str
        :rtype: str
        """
        left, right = equation.split("=")
        left = filter(lambda x: x, left.replace("+", "#P").replace("-", "#M").split("#"))
        right = filter(lambda x: x, right.replace("+", "#M").replace("-", "#P").split("#"))
        left[0] = "P" + left[0] if left[0][0] not in ["P", "M"] else left[0]
        right[0] = "M" + right[0] if right[0][0] not in ["P", "M"] else right[0]
        left += right
        a = b = 0
        for param in left:
          param = param.replace("P", "+").replace("M", "-")
          if param[-1] == "x":
            k = 1
            if len(param) > 2:
              k = int(param[1:-1])
            if param[0] == "-":
              a -= k
            else:
              a += k
          else:
            b -= int(param)
        return "x={0}".format(str(b / a)) if a else "No solution" if b else "Infinite solutions"
    
    

All Problems

All Solutions