Equation Solver

Easy
0/40
Average time to solve is 10m
profile
Contributed by
2 upvotes
Asked in companies
AmazonD.E.Shaw314e Corporation

Problem statement

You are given an equation of the addition of two numbers. One number among the two operands is missing in the given equation and is denoted by ‘x’. You have to find this missing number and return it.

For Example -

Consider the equation x + 10 = 15.
=> x = 15 - 10
=> x = 5 
The output, in this case, is 5.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next ‘T’ lines represent the ‘T’ test cases.

The first and only line of each test case contains a string representing the equation. The given string does not contain any spaces.
Output Format:
For each test case, print the value of ‘x’ in a new line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10^4
-10^9 <= a,b,c <= 10^9 

Where 'a' and 'b' are the numbers that are added together to obtain 'c'.

Time limit: 1 sec
Sample Input 1:
3
x+100=500
78+100=x
10+x=50
Sample Output 1:
400
178
40
Explanation of Sample Input 1:
Test case 1:
The given equation is x+100=500, so the value of ‘x’ is 400

Test case 2:
The given equation is 78+100=x, so the value of ‘x’ is 178

Test case 3:
The given equation is 10+x=50, so the value of ‘x’ is 40
Sample Input 2:
3
x+15=250
25+x=350
125+150=x
Sample Output 2:
235
325
275
Hint

Try to solve the equation by storing each number in a different variable.

Approaches (1)
Solving the equation
  • Declare three string variables ‘FIRST_NUMBER’, ‘SECOND_NUMBER’, ‘THIRD_NUMBER’.
  • Iterate the string from index 0 till just before the ‘+’ character and store it in variable ‘FIRST_NUMBER’.
  • Store the substring starting just after ‘+’ character and ending just before the ‘=’ character in the variable ‘SECOND_NUMBER’.
  • Store the substring starting just after ‘=’ character and till the end in variable ‘THIRD_NUMBER’
  • If the variable ‘FIRST_NUMBER’ is equivalent to ‘X’, then the output is ‘THIRD_NUMBER’ - ‘SECOND_NUMBER’.
  • If the variable ‘SECOND_NUMBER’ is equivalent to ‘X’, then the output is ‘THIRD_NUMBER’ - ‘FIRST_NUMBER’.
  • If the variable ‘THIRD_NUMBER’ is equivalent to ‘X’, then the output is ‘FIRST_NUMBER’ + ‘SECOND_NUMBER’.
Time Complexity

O(N), where ‘N’ is the length of the input string.

 

Since a single iteration is done on the string, the time complexity is O(N).

Space Complexity

O(1)

 

No extra space is required.

Code Solution
(100% EXP penalty)
Equation Solver
Full screen
Console