1709. Balance the Linear Scale

Hard7.5 points estimatedStackMathsString

A balance scale shows an equation in one unknown x. The string equation contains exactly one '=' and, on each side, integers, the letter x, the operators +, - and *, unary minus, and parentheses. Every product has at least one constant factor and is written with an explicit '*' (for example 3*(x-1) or x*4), so each side is a linear expression a*x + b.

Reduce both sides to the form a*x + b, for instance with a stack of (a, b) pairs and an operator stack, then solve. Return "x=p/q" where p/q is the solution in lowest terms with q > 0, or "x=p" when q is 1 (zero is written "x=0"). If every x works return "Infinite solutions"; if no x works return "No solution". Every intermediate coefficient lies within [-10^12, 10^12], so use 64-bit integers. Target O(n) time and O(n) space.

Example 1

Input:
equation = "x+5-3+x=6+x-2"
Output:
"x=2"
Explanation:

The left side is 2x + 2 and the right side is x + 4, so x = 2.

Example 2

Input:
equation = "x=x+1"
Output:
"No solution"
Explanation:

x = x + 1 reduces to 0 = 1, which no value of x satisfies.

Example 3

Input:
equation = "2*x=1"
Output:
"x=1/2"
Explanation:

2x = 1 gives x = 1/2, already in lowest terms.

Constraints

1 ≤ equation.length ≤ 1000

Exactly one '='; no spaces

Every product has a constant factor

Every intermediate coefficient lies in [-1012, 1012]

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…