Nobita has got math assignment to solve. In this assignment, he has to solve a mathematical equation given in the form of a string 'S'. The equation contains only ‘+’ and ‘-’ operators and a variable ‘x’. Nobita doesn’t know how to solve the equation. So, he went to Doremon for help. Doremon gives him a gadget for this. But as usual, Nobita didn’t listen to the instructions to use that gadget.
So, now it's your task to help Nobita find solutions to the given equation, or if there is no solution, report that as well.
Note :If there is no solution for the equation, return "No solution.”
If there is only one solution for the equation, return that solution for ‘x.’
If there are infinite solutions for the equation, return "Infinite solutions.”
‘x’ may or may not have coefficients associated with it.
‘+’, ‘-’, and ‘x’ can occur any number of times in the equation.
The first line contains a single integer ‘T’ representing the number of test cases.
The next ‘T’ lines contain a string ‘S’ representing the equation given to Nobita.
Output Format :
For each test case, print the value of ‘x’, and if the solution doesn’t exist, then print “No solution,” and if there are infinite solutions, then print “Infinite solutions”.
Output for every test case will be printed in a separate line.
Note :
You don’t need to print anything; It has already been taken care of.
1 <= T <= 50
3 <= |S| <= 10^7
-100 <= y <= 100
Time limit: 1 sec
2
x+4=5
x=x
1
Infinite solutions
In test case 1, after shifting 4 from LHS to RHS equation becomes “x = 5 - 4” for which
“x = 1.”
In test case 2, there are infinite values possible for which ‘x’ will be equal to ‘x’. Hence there will be infinite solutions.
2
x=x+5
x+6=0
No solution
-6
Can you think of a solution using the property of mathematical equations?
Each constant and each variable have a corresponding sign to them ‘+’ or ‘-’. So divide the string into two partitions; all that comes before “=” is LHS and after “=” is treated as RHS. Then exclusively use the property of shifting from LHS to RHS or vice versa to solve the equation.
The steps are as follows:
O(|S|), where |S| is the size of the given string ‘S’.
We iterate over the string to create total constants and coefficient sum for both LHS and RHS. Hence the overall time complexity is O(|S|).
O(1)
Constant extra space is used.