Skip to content
Problem 640 · LeetCode 640(opens in a new tab)

Solve the Equation

MediumMath

You get a linear equation in one unknown, x, written as a string such as "2x+3=x-1". Each side is a chain of terms joined by + and -. A term is either a whole number or a number glued to x (its coefficient); a bare x means 1x.

Solve for x. If exactly one value works, return it as "x=<value>". If every value of x works, return "Infinite solutions". If no value works, return "No solution".

Example 1

Input:  equation = "3x-4=x+2"
Output: "x=3"
Why:    move terms over: 2x = 6
2 more examples and the constraints

Example 2

Input:  equation = "2x+1=x+x+1"
Output: "Infinite solutions"
Why:    both sides are the same, 0x = 0

Example 3

Input:  equation = "x+3=x-1"
Output: "No solution"
Why:    the x terms cancel and 3 never equals −1

Constraints

  • 3 ≤ equation.length ≤ 1,000
  • There is exactly one =
  • Numbers are between 0 and 100, written without leading zeros
  • When there is exactly one solution, it is an integer

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Split into termsO(n)
  2. One pass with a side signO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 1,000-character equationVerdict
Split into termsO(n)
Clear; builds extra strings
One pass with a side signO(n)
Best; one read, no copies

n = length of the equation.

Edge cases to test

  • Bare x. x and -x have coefficient 1 and −1; there are no digits to read.
  • Zero coefficient. 0x=5 has coef 0 and num −5 after moving terms: no solution. 0x=0 gives infinite solutions.
  • No x at all. 4=4 is always true (infinite), 4=5 is never true (no solution).
  • Answer is 0 or negative. 3x=x gives "x=0"; 5x+10=0 gives "x=-2".
  • Leading minus. -x=-7 starts with a sign; it must apply to the first term, giving "x=7".

Common mistakes

  • Treating 0x as a bare x and using coefficient 1.
  • Forgetting to flip the sign of every term on the right side of =.
  • Returning "No solution" whenever coef is 0, without checking whether num is also 0.

How to talk through it

  1. 1Clarify. Only + and −, one x, integers 0 to 100? Is a single solution always an integer? What exact strings to return?
  2. 2State the goal. Every linear equation reduces to coef · x + num = 0; I just need those two totals.
  3. 3Give the simple version. Split at = and at the signs, add up each side, subtract right from left.
  4. 4Tighten it. One pass with a side multiplier that flips at =, so no strings are built.
  5. 5Test out loud. Run 0x=0, x+3=x-1, -x=-7 and a term with a two-digit coefficient.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?