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.