Solve the Equation

medium math string

Problem

Given a linear equation like '2x+3x-6x=x+2', return the solution as 'x=...', 'No solution', or 'Infinite solutions'.

Inputequation = 'x+5-3+x=6+x-2'
Output'x=2'
Reduce: 2x + 2 = x + 4 ⇒ x = 2.

def solve_equation(eq):
    def parse(s):
        s = s.replace('-', '+-'); cx = 0; c = 0
        for t in s.split('+'):
            if not t: continue
            if t.endswith('x'):
                v = t[:-1]; cx += -1 if v == '-' else 1 if v in ('', '+') else int(v)
            else: c += int(t)
        return cx, c
    l, r = eq.split('='); lx, lc = parse(l); rx, rc = parse(r)
    a, b = lx - rx, rc - lc
    if a == 0: return 'Infinite solutions' if b == 0 else 'No solution'
    return f'x={b // a}'
function solveEquation(eq) {
  const parse = s => {
    s = s.replace(/-/g, '+-'); let cx = 0, c = 0;
    for (const t of s.split('+')) {
      if (!t) continue;
      if (t.endsWith('x')) { const v = t.slice(0, -1); cx += v === '-' ? -1 : (v === '' || v === '+') ? 1 : +v; }
      else c += +t;
    }
    return [cx, c];
  };
  const [L, R] = eq.split('='); const [lx, lc] = parse(L); const [rx, rc] = parse(R);
  const a = lx - rx, b = rc - lc;
  if (a === 0) return b === 0 ? 'Infinite solutions' : 'No solution';
  return 'x=' + Math.trunc(b / a);
}
String solveEquation(String eq) {
    int[] L = parse(eq.split("=")[0]), R = parse(eq.split("=")[1]);
    int a = L[0] - R[0], b = R[1] - L[1];
    if (a == 0) return b == 0 ? "Infinite solutions" : "No solution";
    return "x=" + (b / a);
}
int[] parse(String s) {
    s = s.replace("-", "+-"); int cx = 0, c = 0;
    for (String t : s.split("\\+")) {
        if (t.isEmpty()) continue;
        if (t.endsWith("x")) { String v = t.substring(0, t.length()-1); cx += v.equals("-") ? -1 : (v.isEmpty() || v.equals("+") ? 1 : Integer.parseInt(v)); }
        else c += Integer.parseInt(t);
    }
    return new int[]{cx, c};
}
pair parse(string s) {
    string r; for (char c : s) { if (c == '-') r += "+-"; else r += c; }
    int cx = 0, c = 0; stringstream ss(r); string t;
    while (getline(ss, t, '+')) {
        if (t.empty()) continue;
        if (t.back() == 'x') { string v = t.substr(0, t.size()-1); cx += v == "-" ? -1 : (v.empty() || v == "+" ? 1 : stoi(v)); }
        else c += stoi(t);
    }
    return {cx, c};
}
string solveEquation(string eq) {
    int eq_pos = eq.find('='); auto L = parse(eq.substr(0, eq_pos)), R = parse(eq.substr(eq_pos + 1));
    int a = L.first - R.first, b = R.second - L.second;
    if (a == 0) return b == 0 ? "Infinite solutions" : "No solution";
    return "x=" + to_string(b / a);
}
Time: O(n) Space: O(n)