![]() |
VOOZH | about |
Given a linear equation, task is to find the value of variable used. The equation contains only '+', '-' operation, the variable and its coefficient.
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.
x = 2
Time complexity : O(n), where n is the length of equation string. Auxiliary Space : O(1)