Ctrl K

Solve for x

Medium
You are given a linear equation equation in one variable x. Each side is a sum of terms joined by + and -; a term is a non-negative integer or x with an optional coefficient in front of it (x, 0x, 7x). The first term on a side may also carry a sign. Solve the equation and return: - "x=<value>" if there is exactly one solution (it is guaranteed to be an integer); - "No solution" if there are no solutions; - "Infinite solutions" if every x works.
Example 1
equation="3x-7=x+5" → 'x=6'

Moving terms across gives 3x − x = 5 + 7, so 2x = 12 and x = 6.

Example 2
equation="x+x-4=2x" → 'No solution'

The left side is 2x − 4 and the right side is 2x; x cancels out and leaves −4 = 0, so there is no solution.

Example 3
equation="10-x=10-x" → 'Infinite solutions'

Both sides are identical, so every x works.

Constraints
  • 3 ≤ len(equation) ≤ 1000
  • equation has exactly one = and both sides are non-empty
  • equation consists of digits, +, - and x
  • Numbers and coefficients are between 0 and 100, with no leading zeros
  • If the solution is unique, it is an integer
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMultiplying Digit Strings MediumMultiply Complex Numbers in Strings MediumTotal of a Fraction Chain MediumRover on Repeat MediumSum of Binary Strings Easy
loading Python…
Input
equation="3x-7=x+5"
Expected
'x=6'

Run checks the first 3 tests in your browser. Submit checks all 193 tests on the server, hidden ones included.