We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Solve the Equation

Number: 640

Difficulty: Medium

Paid? No

Companies: Amazon


Problem Description

Given a linear equation with one variable x that includes only addition, subtraction, and the variable x with its coefficients (e.g., "2x", "x", etc.), determine the integer value of x if a unique solution exists. If the equation has no solution or infinitely many solutions, return "No solution" or "Infinite solutions" respectively. The answer should be formatted as "x=#value" when there is a unique solution.


Key Insights

  • Split the equation into left and right parts at the '=' sign.
  • Parse each side to extract the cumulative coefficient of x and the constant term.
  • Translate the equation into the form: (coefficient_difference) * x = (constant_difference).
  • Handle special cases:
    • If the coefficient difference is zero and the constant difference is also zero then there are infinite solutions.
    • If the coefficient difference is zero but the constant difference is non-zero then there is no solution.
  • If a valid unique solution exists, compute it as an integer.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the equation string. Space Complexity: O(1), using only constant extra space.


Solution

The solution involves splitting the input equation by the '=' delimiter into the left-hand side (LHS) and right-hand side (RHS). For each side, iterate through the characters to identify tokens representing either a constant number or a term with the variable x. Care is taken to correctly process signs, handle the implicit coefficient of 1 in terms like "x" or "-x", and correctly sum the coefficients and constants. After parsing both sides, rearrange the equation into the form (left_x - right_x) * x = (right_constant - left_constant) and then determine:

  • Unique solution: if the coefficient difference is non-zero.
  • Infinite solutions: if both differences are zero.
  • No solution: if the coefficient is zero but the constant difference is non-zero.

Code Solutions

# Define the function to solve the equation
def solveEquation(equation):
    # Helper function to parse one side of the equation
    def parse_side(expr):
        coef, const = 0, 0
        i, n = 0, len(expr)
        sign = 1
        while i < n:
            # Determine the current sign
            if expr[i] == '+':
                sign = 1
                i += 1
            elif expr[i] == '-':
                sign = -1
                i += 1
            num = 0
            valid_num = False
            # Process all digits if present
            while i < n and expr[i].isdigit():
                num = num * 10 + int(expr[i])
                i += 1
                valid_num = True
            # Check if the term involves variable 'x'
            if i < n and expr[i] == 'x':
                # If no explicit number, treat as 1
                coef += sign * (num if valid_num else 1)
                i += 1
            else:
                # It's a constant term
                const += sign * num
        return coef, const

    # Split the equation into left and right parts
    left, right = equation.split("=")
    left_coef, left_const = parse_side(left)
    right_coef, right_const = parse_side(right)
    
    # Bring the x terms to one side and constants to the other
    coef = left_coef - right_coef
    const = right_const - left_const
    
    # Determine the nature of the solution
    if coef == 0:
        if const == 0:
            return "Infinite solutions"
        else:
            return "No solution"
    # Calculate and return the unique integer solution
    return "x=" + str(const // coef)

# Example usage:
# print(solveEquation("x+5-3+x=6+x-2"))
← Back to All Questions