You are given a string that represents an equation of the form ax + b = cx + d
where:
a
, b
, c
, and d
are integers, andx
is the variable in question.Your task is to solve for x
.
If there is a solution for x
, return it as a string in the form "x=#value"
, where #value
is an integer. If there are infinite solutions, return "Infinite solutions"
. If there is no solution, return "No solution"
.
Input: "x+5-3+x=6+x-2"
Output: "x=2"
Input: "x=x"
Output: "Infinite solutions"
Input: "2x=x"
Output: "x=0"
Input: "2x+3x-6x=x+2"
Output: "x=-1"
Input: "x=x+2"
Output: "No solution"
=
sign to separate it into the left-hand side (LHS) and the right-hand side (RHS).x
and the constant term from the string.x
and constants for both sides of the equation.x
on both sides are the same, check the constants:
"Infinite solutions"
."No solution"
.x
.Here’s a complete Python code implementing the strategy:
def solveEquation(equation: str) -> str:
def parse_expr(expr):
# Initialize variables to hold the sum of x coefficients and constant term
x_coeff = 0
const = 0
num = 0
sign = 1 # 1 means positive sign, -1 means negative sign
i = 0
n = len(expr)
while i < n:
if expr[i] == '+':
sign = 1
i += 1
elif expr[i] == '-':
sign = -1
i += 1
elif expr[i] == 'x':
# Check if 'x' is preceded by a number
if i == 0 or not expr[i-1].isdigit():
# The coefficient before 'x' is either 1 or -1
x_coeff += sign
else:
x_coeff += sign * num
num = 0
i += 1
else:
num = 0
while i < n and expr[i].isdigit():
num = num * 10 + int(expr[i])
i += 1
if i < n and expr[i] == 'x':
x_coeff += sign * num
i += 1
else:
const += sign * num
num = 0
return x_coeff, const
# Split the equation into LHS and RHS
lhs, rhs = equation.split('=')
lhs_x_coeff, lhs_const = parse_expr(lhs)
rhs_x_coeff, rhs_const = parse_expr(rhs)
# Calculate the net coefficients and constant term
net_x_coeff = lhs_x_coeff - rhs_x_coeff
net_const = rhs_const - lhs_const
if net_x_coeff == 0:
if net_const == 0:
return "Infinite solutions"
else:
return "No solution"
else:
x_value = net_const // net_x_coeff
return f"x={x_value}"
# Test the function with a sample input
equation = "x+5-3+x=6+x-2"
print(solveEquation(equation)) # Output: "x=2"
The time complexity of this solution is O(n), where n
is the length of the input string. This is because we are processing each character in the string exactly once during the parsing steps.
Let me know if you have any further questions or need additional clarifications!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?