Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

640. Solve the Equation - Leetcode Solution

Code Implementation

class Solution:
    def solveEquation(self, equation: str) -> str:
        def parse(expr):
            coef, const, i, sign = 0, 0, 0, 1
            n = len(expr)
            while i < n:
                if expr[i] == '+':
                    sign = 1
                    i += 1
                elif expr[i] == '-':
                    sign = -1
                    i += 1
                else:
                    j = i
                    while j < n and expr[j].isdigit():
                        j += 1
                    num = int(expr[i:j]) if j > i else 1
                    if j < n and expr[j] == 'x':
                        coef += sign * num
                        j += 1
                    else:
                        const += sign * num
                    i = j
            return coef, const

        left, right = equation.split('=')
        lcoef, lconst = parse(left)
        rcoef, rconst = parse(right)
        coef = lcoef - rcoef
        const = rconst - lconst
        if coef == 0:
            if const == 0:
                return "Infinite solutions"
            else:
                return "No solution"
        else:
            return f"x={const // coef}"
      
class Solution {
public:
    string solveEquation(string equation) {
        auto parse = [](const string& expr) {
            int coef = 0, constant = 0, sign = 1, i = 0, n = expr.size();
            while (i < n) {
                if (expr[i] == '+') {
                    sign = 1;
                    i++;
                } else if (expr[i] == '-') {
                    sign = -1;
                    i++;
                } else {
                    int j = i, num = 0, hasNum = 0;
                    while (j < n && isdigit(expr[j])) {
                        num = num * 10 + (expr[j] - '0');
                        j++;
                        hasNum = 1;
                    }
                    if (j < n && expr[j] == 'x') {
                        coef += sign * (hasNum ? num : 1);
                        j++;
                    } else {
                        constant += sign * (hasNum ? num : 0);
                    }
                    i = j;
                }
            }
            return make_pair(coef, constant);
        };
        int eq = equation.find('=');
        auto left = parse(equation.substr(0, eq));
        auto right = parse(equation.substr(eq + 1));
        int coef = left.first - right.first;
        int constant = right.second - left.second;
        if (coef == 0) {
            if (constant == 0) return "Infinite solutions";
            else return "No solution";
        }
        return "x=" + to_string(constant / coef);
    }
};
      
class Solution {
    public String solveEquation(String equation) {
        int[] left = parse(equation.split("=")[0]);
        int[] right = parse(equation.split("=")[1]);
        int coef = left[0] - right[0];
        int constVal = right[1] - left[1];
        if (coef == 0) {
            if (constVal == 0) return "Infinite solutions";
            else return "No solution";
        }
        return "x=" + (constVal / coef);
    }
    
    private int[] parse(String expr) {
        int coef = 0, constant = 0, sign = 1, i = 0, n = expr.length();
        while (i < n) {
            if (expr.charAt(i) == '+') {
                sign = 1;
                i++;
            } else if (expr.charAt(i) == '-') {
                sign = -1;
                i++;
            } else {
                int j = i, num = 0, hasNum = 0;
                while (j < n && Character.isDigit(expr.charAt(j))) {
                    num = num * 10 + (expr.charAt(j) - '0');
                    j++;
                    hasNum = 1;
                }
                if (j < n && expr.charAt(j) == 'x') {
                    coef += sign * (hasNum == 1 ? num : 1);
                    j++;
                } else {
                    constant += sign * (hasNum == 1 ? num : 0);
                }
                i = j;
            }
        }
        return new int[] {coef, constant};
    }
}
      
var solveEquation = function(equation) {
    function parse(expr) {
        let coef = 0, constant = 0, sign = 1, i = 0, n = expr.length;
        while (i < n) {
            if (expr[i] === '+') {
                sign = 1;
                i++;
            } else if (expr[i] === '-') {
                sign = -1;
                i++;
            } else {
                let j = i, num = 0, hasNum = false;
                while (j < n && /\d/.test(expr[j])) {
                    num = num * 10 + parseInt(expr[j]);
                    j++;
                    hasNum = true;
                }
                if (j < n && expr[j] === 'x') {
                    coef += sign * (hasNum ? num : 1);
                    j++;
                } else {
                    constant += sign * (hasNum ? num : 0);
                }
                i = j;
            }
        }
        return [coef, constant];
    }
    let [left, right] = equation.split('=');
    let [lcoef, lconst] = parse(left);
    let [rcoef, rconst] = parse(right);
    let coef = lcoef - rcoef;
    let constant = rconst - lconst;
    if (coef === 0) {
        if (constant === 0) return "Infinite solutions";
        else return "No solution";
    }
    return "x=" + (constant / coef);
};
      

Problem Description

You are given a string equation representing a linear equation in one variable x. The equation contains integer coefficients, the variable x, plus and minus signs, and an equals sign (=). Your task is to find the value of x that satisfies the equation.

The equation is always valid and formatted as left side = right side. You must return:

  • "x=#value" if there is a unique solution for x
  • "Infinite solutions" if there are infinite solutions (the two sides are always equal)
  • "No solution" if there is no possible value for x that satisfies the equation
The equation may contain terms like 2x, -x, +3, etc. The coefficients and constants are integers. There is always exactly one variable x in the equation.

Thought Process

At first glance, this problem looks like a typical algebraic manipulation. But as a programmer, we need to parse and interpret the string to extract coefficients and constants.

A brute-force approach might try to evaluate values for x until the equation balances, but this is inefficient and unnecessary. Instead, we can "collect like terms" as we would on paper: move all terms involving x to one side and all constants to the other, then solve for x.

The main challenge is correctly parsing the string, handling signs, and distinguishing between coefficients of x and constants. We need to:

  • Go through each term on both sides of the equation
  • Sum up all coefficients of x
  • Sum up all constants
  • Then, solve for x using simple algebra
This is a shift from brute-force trial to systematic parsing and reduction.

Solution Approach

Let's break down the steps to solve the equation programmatically:

  1. Split the equation: Use the = sign to divide the equation into left and right parts.
  2. Parse each side: For both sides, process the string to:
    • Extract and sum coefficients of x
    • Extract and sum constant terms
    This involves iterating through the string, detecting numbers, signs, and the variable x.
  3. Combine terms: Move all x terms to one side (subtract right from left) and all constants to the other (subtract left from right).
  4. Solve for x:
    • If the coefficient of x is zero:
      • If the constant is also zero, return "Infinite solutions"
      • Otherwise, return "No solution"
    • Otherwise, return "x=#value" where #value is the integer result of dividing the constants by the coefficient.

We use simple arithmetic and string parsing for this, and no advanced data structures are required.

Example Walkthrough

Let's use the example "x+5-3+x=6+x-2".

  • Split into left: "x+5-3+x", right: "6+x-2"
  • Parse left:
    • x: coefficient +1
    • +5: constant +5
    • -3: constant -3
    • +x: coefficient +1
    • Total: coefficient = 2, constant = 2
  • Parse right:
    • 6: constant +6
    • +x: coefficient +1
    • -2: constant -2
    • Total: coefficient = 1, constant = 4
  • Bring x terms to one side: 2 - 1 = 1
  • Bring constants to the other: 4 - 2 = 2
  • Solve: x = 2
  • Return: "x=2"

Time and Space Complexity

Brute-force approach: Trying every possible integer value for x is extremely inefficient, potentially O(N) for N possible values.

Optimized parsing approach: We scan each character of the equation once to parse coefficients and constants. Thus:

  • Time Complexity: O(N), where N is the length of the equation string.
  • Space Complexity: O(1), since we only use a fixed number of integer variables for sums.
This is efficient and suitable for large equations.

Summary

The key to solving the "Solve the Equation" problem is to treat the equation like an algebraic expression: parse both sides, collect like terms, and solve for x. By methodically extracting coefficients and constants with a string parser, we avoid brute-force and achieve an elegant O(N) solution. This approach combines basic string processing with algebraic manipulation, making it efficient and reliable.