linear equations
algorithm
mathematics
problem solving
algebra

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:

text
ax + b = cx + d

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 2 for x
  • 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).

python
1def parse_side(expr: str) -> tuple[int, int]:
2    coeff = 0
3    const = 0
4    i = 0
5    sign = 1
6
7    while i < len(expr):
8        if expr[i] == '+':
9            sign = 1
10            i += 1
11        elif expr[i] == '-':
12            sign = -1
13            i += 1
14        else:
15            num = 0
16            has_digits = False
17
18            while i < len(expr) and expr[i].isdigit():
19                num = num * 10 + int(expr[i])
20                i += 1
21                has_digits = True
22
23            if i < len(expr) and expr[i] == 'x':
24                coeff += sign * (num if has_digits else 1)
25                i += 1
26            else:
27                const += sign * num
28
29    return coeff, const

This handles terms such as x, 2x, -x, and regular numbers.

Solve the Whole Equation

Once both sides are parsed, solving is just arithmetic.

python
1def solve_equation(equation: str) -> str:
2    left, right = equation.split('=')
3
4    left_coeff, left_const = parse_side(left)
5    right_coeff, right_const = parse_side(right)
6
7    coeff = left_coeff - right_coeff
8    const = right_const - left_const
9
10    if coeff == 0:
11        if const == 0:
12            return "Infinite solutions"
13        return "No solution"
14
15    return f"x={const // coeff}"

Example:

python
print(solve_equation("x+5-3+x=6+x-2"))
print(solve_equation("x=x"))
print(solve_equation("2x=x"))

Output:

text
x=2
Infinite solutions
x=0

Why the Three Cases Exist

After rearranging, every equation reduces to:

text
coeff * x = const

There are only three outcomes:

  • 'coeff != 0 gives one solution'
  • 'coeff == 0 and const == 0 gives infinitely many solutions'
  • 'coeff == 0 and const != 0 gives no solution'

That is why the algorithm is so reliable once parsing is done correctly.

Worked Example

Take:

text
2x+3=x+8

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:

text
x = 5

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 x and 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.

Course illustration
Course illustration

All Rights Reserved.