VOOZH about

URL: https://www.geeksforgeeks.org/dsa/solve-the-linear-equation-of-single-variable/

⇱ Solve the Linear Equation of Single Variable - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Solve the Linear Equation of Single Variable

Last Updated : 24 Jun, 2024

Given a linear equation, task is to find the value of variable used. The equation contains only '+', '-' operation, the variable and its coefficient.

  1. If there is no solution for the equation, return "No solution".
  2. If there are infinite solutions for the equation, return "Infinite solutions".
  3. If there is exactly one solution for the equation, ensure that the value of x is an integer.

Examples :

Input : "x + 5 - 3 + x = 6 + x - 2"
Output : "x = 2"
Input : "x = x"
Output : "Infinite solutions"
Input: "2x = x"
Output: "x = 0"
Input: "x = x + 2"
Output: "No solution"

Approach : The idea is to use two pointers to update two parameters: the coefficient of variable used and the total sum. On the left and right side of ‘=’, use opposite signs for each numbers which is taken care of by a sign variable, which will flip once ‘=’ is seen. Now, in case of a unique solution, the ratio of the effective total and coefficient gives the required result. In case of infinite solutions, both the effective total and coefficient turns out to be zero e.g. x + 1 = x + 1. In case of no solution, the coefficient of x turns out to be zero, but the effective total is non-zero. 


Output
x = 2

Time complexity : O(n), where n is the length of equation string. Auxiliary Space : O(1)

Comment