Solve the Equation - Problem

Solve a given equation and return the value of 'x' in the form of a string "x=#value".

The equation contains only '+' and '-' operations, the variable 'x' and its coefficient.

Return cases:

  • "No solution" if there is no solution for the equation
  • "Infinite solutions" if there are infinite solutions for the equation
  • "x=#value" if there is exactly one solution (where #value is an integer)

Input & Output

Example 1 — Basic Case
$ Input: equation = "x+5-3+x=6+x-2"
Output: "x=2"
💡 Note: Left side: x + x + 5 - 3 = 2x + 2. Right side: 6 + x - 2 = x + 4. Moving terms: 2x - x = 4 - 2, so x = 2.
Example 2 — No Solution
$ Input: equation = "x=x"
Output: "Infinite solutions"
💡 Note: Both sides are identical (x = x), so any value of x satisfies the equation.
Example 3 — Contradictory
$ Input: equation = "2x=x"
Output: "x=0"
💡 Note: Moving terms: 2x - x = 0, so x = 0.

Constraints

  • The equation contains only '+', '-' operation, the variable 'x' and its coefficient
  • There is exactly one '=' in the equation
  • The equation is valid and follows the format described

Visualization

Tap to expand
Solve the Equation - String Parsing INPUT x+5-3+x=6+x-2 Split at '=' sign LHS x+5-3+x RHS 6+x-2 Parse Tokens +x +5 -3 +x +6 +x -2 Goal: Find x value Move all x to left side Move all constants to right Solve: coeff * x = constant ALGORITHM STEPS 1 Parse LHS coeff_x = 2, const = 2 +x --> coeff_x += 1 +5-3 --> const += 2 +x --> coeff_x += 1 = 2 2 Parse RHS coeff_x = 1, const = 4 +6-2 --> const = 4 +x --> coeff_x = 1 3 Move Terms Subtract RHS from LHS x_coeff = 2 - 1 = 1 const = 4 - 2 = 2 1*x = 2 4 Solve x = const / coeff x = 2 / 1 = 2 Result: "x=2" FINAL RESULT Verification x+5-3+x = 6+x-2 Substitute x = 2 LHS 2+5-3+2 = 6 RHS 6+2-2 = 6 = OK - Valid OUTPUT "x=2" Edge Cases coeff=0, const=0 --> "Infinite solutions" coeff=0, const!=0 --> "No solution" Key Insight: Track sign changes while parsing: When encountering '+' or '-', apply the current sign to the accumulated number/coefficient. For RHS, negate all values to effectively move them to LHS. Final equation: (coeff_left - coeff_right) * x = (const_right - const_left) TutorialsPoint - Solve the Equation | String Parsing with Sign Tracking
Asked in
Google 15 Amazon 12
23.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen