#640

Solve the Equation

Medium
MathStringSimulationString ManipulationMathematical Equations
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution involves a single pass through the equation to calculate the coefficients of 'x' and the constant terms. This approach is efficient as it avoids unnecessary iterations and directly computes the result.

⚙️

Algorithm

4 steps
  1. 1Step 1: Split the equation into left and right parts using '='.
  2. 2Step 2: Initialize variables to track the coefficients of 'x' and the constant terms for both sides.
  3. 3Step 3: Iterate through the equation once, updating the coefficients and constants based on the current character and its sign.
  4. 4Step 4: Calculate the total coefficients and constants, and determine the solution based on their values.
solution.py26 lines
1def solveEquation(equation):
2    left, right = equation.split('=')
3    coeff, const = 0, 0
4    sign = 1
5    for side in [left, right]:
6        i = 0
7        while i < len(side):
8            if side[i] == '+':
9                sign = 1
10                i += 1
11            elif side[i] == '-':
12                sign = -1
13                i += 1
14            num = 0
15            while i < len(side) and side[i].isdigit():
16                num = num * 10 + int(side[i])
17                i += 1
18            if i < len(side) and side[i] == 'x':
19                coeff += sign * (num if num else 1)
20                i += 1
21            else:
22                const += sign * num
23        const *= -1  # Reverse sign for right side
24    if coeff == 0:
25        return 'Infinite solutions' if const == 0 else 'No solution'
26    return f'x={const // coeff}'

Complexity note: The complexity is O(n) because we only make a single pass through the equation to compute the coefficients and constants.

  • 1Understanding how to parse and manipulate strings is crucial for solving equations.
  • 2Recognizing that coefficients and constants can be separated helps in simplifying the problem.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.