Skip to main content
Back to problems
#640
Medium Algorithms

Solve the equation

Math String Simulation
46.1% acceptance
Feb 20, 2026
547
854
Solve a given equation and return the value of 'x'. Return "No solution" or "Infinite solutions" if applicable.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn solve_equation(equation: String) -> String {
    fn parse(s: &str) -> (i32, i32) {
      // returns (coeff_x, constant)
      let mut coeff = 0i32;
      let mut constant = 0i32;
      let bytes = s.as_bytes();
      let mut i = 0;
      let mut sign = 1i32;
      while i < bytes.len() {
        if bytes[i] == b'+' {
          sign = 1;
          i += 1;
        } else if bytes[i] == b'-' {
          sign = -1;
          i += 1;
        } else {
          // read number (possibly empty before 'x')
          let mut num = 0i32;
          let mut has_digit = false;
          while i < bytes.len() && bytes[i].is_ascii_digit() {
            num = num * 10 + (bytes[i] - b'0') as i32;
            has_digit = true;
            i += 1;
          }
          if i < bytes.len() && bytes[i] == b'x' {
            coeff += sign * if has_digit { num } else { 1 };
            i += 1;
          } else {
            constant += sign * num;
          }
        }
      }
      (coeff, constant)
    }
    let eq: Vec<&str> = equation.split('=').collect();
    let (lc, lk) = parse(eq[0]);
    let (rc, rk) = parse(eq[1]);
    let coeff = lc - rc;
    let constant = rk - lk;
    if coeff == 0 {
      if constant == 0 {
        "Infinite solutions".to_string()
      } else {
        "No solution".to_string()
      }
    } else {
      format!("x={}", constant / coeff)
    }
  }
}