Algorithm - solving linear equation in one variable
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
For a programming problem, “solving a linear equation in one variable” usually means taking an input string such as x+5-3+x=6+x-2 and computing the value of x. The clean algorithm is to reduce both sides into the form ax + b, then compare the two sides to decide whether the equation has one solution, no solution, or infinitely many solutions.
Reduce Each Side to Coefficient and Constant
A linear equation in one variable can always be reorganized into:
Instead of doing symbolic algebra with complicated objects, you can parse each side and compute two numbers:
- the coefficient of
x - the constant term
For example, the left side of x+5-3+x becomes:
- coefficient
2forx - constant
2
Parsing Strategy
Walk through the string token by token. Track the current sign, read numbers, and distinguish between plain constants and terms ending in x.
A useful parser returns a pair (coefficient, constant).
This handles terms such as x, 2x, -x, and regular numbers.
Solve the Whole Equation
Once both sides are parsed, solving is just arithmetic.
Example:
Output:
Why the Three Cases Exist
After rearranging, every equation reduces to:
There are only three outcomes:
- '
coeff != 0gives one solution' - '
coeff == 0andconst == 0gives infinitely many solutions' - '
coeff == 0andconst != 0gives no solution'
That is why the algorithm is so reliable once parsing is done correctly.
Worked Example
Take:
Parsed form:
- left side is
(2, 3) - right side is
(1, 8)
Subtract right from left:
- coefficient becomes
1 - constant becomes
5
So the equation becomes:
The code reaches the same result automatically.
Complexity
The parser walks each character once, so the runtime is linear in the length of the equation string.
That makes the approach efficient enough even for long expressions.
Common Pitfalls
A common mistake is mishandling bare x or -x. Those terms mean coefficient 1 and -1, not 0.
Another pitfall is trying to evaluate the expression numerically instead of collecting coefficients and constants separately.
Developers also sometimes forget the special cases for no solution and infinite solutions.
Finally, if integer division is used, the problem must guarantee an integer answer. If not, the output format needs to handle rational results explicitly.
Summary
- Parse each side of the equation into a coefficient of
xand a constant term. - Reduce the equation to the form
ax + b = cx + d. - Move variable terms to one side and constants to the other.
- Handle the three cases: unique solution, no solution, and infinite solutions.
- A single linear scan parser is enough for this problem.

