Solve the Linear Equation of Single Variable

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.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to solve the given equation
#include <bits/stdc++.h>
using namespace std;
  
// Function to solve the given equation
string solveEquation(string equation)
{
    int n = equation.size(), sign = 1, coeff = 0;
    int total = 0, i = 0;
  
    // Traverse the equation
    for (int j = 0; j < n; j++) {
        if (equation[j] == '+' || equation[j] == '-') {
            if (j > i)
                total += sign * stoi(equation.substr(i, j - i));
            i = j;
        }
  
        // For cases such as: x, -x, +x
        else if (equation[j] == 'x') {
            if ((i == j) || equation[j - 1] == '+')
                coeff += sign;
            else if (equation[j - 1] == '-')
                coeff -= sign;
            else
                coeff += sign * stoi(equation.substr(i, j - i));
            i = j + 1;
        }
  
        // Flip sign once '=' is seen
        else if (equation[j] == '=') {
            if (j > i)
                total += sign * stoi(equation.substr(i, j - i));
            sign = -1;
            i = j + 1;
        }
    }
  
    // There may be a number left in the end
    if (i < n)
        total += sign * stoi(equation.substr(i));
  
    // For infinite solutions
    if (coeff == 0 && total == 0)
        return "Infinite solutions";
  
    // For no solution
    if (coeff == 0 && total)
        return "No solution";
  
    // x = total sum / coeff of x
    // '-' sign indicates moving
    // numeric value to right hand side
    int ans = -total / coeff;
    return "x=" + to_string(ans);
}
  
// Driver code
int main()
{
    string equation = "x+5-3+x=6+x-2";
    cout << solveEquation(equation);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to solve
// the given equation
import java.io.*;
  
class GFG
{
// Function to solve 
// the given equation
static String solveEquation(String equation)
{
    int n = equation.length(), 
        sign = 1, coeff = 0;
    int total = 0, i = 0;
  
    // Traverse the equation
    for (int j = 0; j < n; j++) 
    {
        if (equation.charAt(j) == '+' || 
            equation.charAt(j) == '-')
        {
            if (j > i)
                total += sign * 
                         Integer.parseInt(
                                 equation.substring(i, j));
            i = j;
        }
  
        // For cases such 
        // as: x, -x, +x
        else if (equation.charAt(j) == 'x')
        {
            if ((i == j) || 
                 equation.charAt(j - 1) == '+')
                coeff += sign;
                  
            else if (equation.charAt(j - 1) == '-')
                coeff -= sign;
                  
            else
                coeff += sign * 
                         Integer.parseInt(
                                 equation.substring(i, j));
            i = j + 1;
        }
  
        // Flip sign once 
        // '=' is seen
        else if (equation.charAt(j) == '='
        {
            if (j > i)
                total += sign * 
                         Integer.parseInt(
                                 equation.substring(i, j));
            sign = -1;
            i = j + 1;
        }
    }
  
    // There may be a 
    // number left in the end
    if (i < n)
        total = total + 
                sign * 
                Integer.parseInt(
                        equation.substring(i));
  
    // For infinite
    // solutions
    if (coeff == 0 && 
        total == 0)
        return "Infinite solutions";
  
    // For no solution
    if (coeff == 0 && 
        total != 0)
        return "No solution";
  
    // x = total sum / coeff 
    // of x '-' sign indicates 
    // moving numeric value to 
    // right hand side
    int ans = -total / coeff;
    return (Integer.toString(ans));
}
  
// Driver code
public static void main(String args[])
{
    String equation = new String("x+5-3+x=6+x-2");
    System.out.print("x = "
                      solveEquation(equation));
}
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to solve
# the given equation
  
# def to solve 
# the given equation
def solveEquation(equation) :
  
    n = len(equation) 
    sign = 1
    coeff = 0
    total = 0
    i = 0
  
    # Traverse the equation
    for j in range(0, n) :
      
        if (equation[j] == '+' or
            equation[j] == '-') :
          
            if (j > i) :
                total = (total + sign * 
                         int(equation[i: j]))
            i = j
          
        # For cases such 
        # as: x, -x, +x
        elif (equation[j] == 'x') :
          
            if ((i == j) or
                equation[j - 1] == '+') :
                coeff += sign
            elif (equation[j - 1] == '-') :
                coeff = coeff - sign
            else :
                coeff = (coeff + sign * 
                         int(equation[i: j]))
            i = j + 1
          
        # Flip sign once 
        # '=' is seen
        elif (equation[j] == '=') :
          
            if (j > i) :
                total = (total + sign * 
                         int(equation[i: j]))
            sign = -1
            i = j + 1
          
    # There may be a number
    # left in the end
    if (i < n) :
        total = (total + sign * 
                 int(equation[i: len(equation)]))
  
    # For infinite solutions
    if (coeff == 0 and
        total == 0) :
        return "Infinite solutions"
  
    # For no solution
    if (coeff == 0 and total) :
        return "No solution"
  
    # x = total sum / coeff of x
    # '-' sign indicates moving
    # numeric value to right hand side
    ans = -total / coeff
    return int(ans)
  
# Driver code
equation = "x+5-3+x=6+x-2"
print ("x = {}"
        format(solveEquation(equation)))
  
# This code is contributed by 
# Manish Shaw(manishshaw1)

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to solve
// the given equation
using System;
  
class GFG
{
    // Function to solve 
    // the given equation
    static string solveEquation(string equation)
    {
        int n = equation.Length, 
            sign = 1, coeff = 0;
        int total = 0, i = 0;
      
        // Traverse the equation
        for (int j = 0; j < n; j++) 
        {
            if (equation[j] == '+' || 
                equation[j] == '-')
            {
                if (j > i)
                    total += sign * 
                             Int32.Parse(
                             equation.Substring(i, j - i));
                i = j;
            }
      
            // For cases such 
            // as: x, -x, +x
            else if (equation[j] == 'x')
            {
                if ((i == j) || 
                     equation[j - 1] == '+')
                    coeff += sign;
                      
                else if (equation[j - 1] == '-')
                    coeff -= sign;
                      
                else
                    coeff += sign * 
                             Int32.Parse(
                             equation.Substring(i, j - i));
                i = j + 1;
            }
      
            // Flip sign once 
            // '=' is seen
            else if (equation[j] == '='
            {
                if (j > i)
                    total += sign * 
                             Int32.Parse(
                             equation.Substring(i, j - i));
                sign = -1;
                i = j + 1;
            }
        }
      
        // There may be a 
        // number left in the end
        if (i < n)
            total += sign * 
                     Int32.Parse(
                     equation.Substring(i));
      
        // For infinite
        // solutions
        if (coeff == 0 && total == 0)
            return "Infinite solutions";
      
        // For no solution
        if (coeff == 0 && total != 0)
            return "No solution";
      
        // x = total sum / coeff 
        // of x '-' sign indicates 
        // moving numeric value to 
        // right hand side
        int ans = -total / coeff;
        return "x = " + ans.ToString();
    }
      
    // Driver code
    static void Main()
    {
        string equation = "x+5-3+x=6+x-2";
        Console.Write(solveEquation(equation));
    }
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to solve
// the given equation
  
// Function to solve 
// the given equation
function solveEquation($equation)
{
    $n = strlen($equation); 
    $sign = 1; $coeff = 0;
    $total = 0; $i = 0;
  
    // Traverse the equation
    for ($j = 0; $j < $n; $j++) 
    {
        if ($equation[$j] == '+' || 
            $equation[$j] == '-')
        {
            if ($j > $i)
                $total += $sign
                          intval(substr($equation
                                        $i, $j - $i));
            $i = $j;
        }
  
        // For cases such 
        // as: x, -x, +x
        else if ($equation[$j] == 'x'
        {
            if (($i == $j) || 
                 $equation[$j - 1] == '+')
                $coeff += $sign;
            else if ($equation[$j - 1] == '-')
                $coeff -= $sign;
            else
                $coeff += $sign
                          intval(substr($equation
                                        $i, $j - $i));
            $i = $j + 1;
        }
  
        // Flip sign once 
        // '=' is seen
        else if ($equation[$j] == '='
        {
            if ($j > $i)
                $total += $sign
                          intval(substr($equation
                                        $i, $j - $i));
            $sign = -1;
            $i = $j + 1;
        }
    }
  
    // There may be a number
    // left in the end
    if ($i < $n)
        $total += $sign
                  intval(substr($equation, $i));
  
    // For infinite solutions
    if ($coeff == 0 && 
        $total == 0)
        return "Infinite solutions";
  
    // For no solution
    if ($coeff == 0 && $total)
        return "No solution";
  
    // x = total sum / coeff of x
    // '-' sign indicates moving
    // numeric value to right hand side
    $ans = -$total / $coeff;
    return "x = " . $ans;
}
  
// Driver code
$equation = "x+5-3+x=6+x-2";
echo (solveEquation($equation));
  
// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

chevron_right


Output:

x = 2

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : manishshaw1



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.