Satisfiability of Equality Equations in C++

C++Server Side ProgrammingProgramming

Suppose we have an array if equations that represent relationships between variables, now each string equations[i] has the length 4 and takes one of two different forms: "a==b" or "a!=b". Here, a and b are lowercase letters, that are representing one-letter variable names. So we have to find true if and only if it is possible to assign integers to variable names so as to satisfy all the given equations.

If the input is like: ["a==b","b==c","a==c"], then the answer will be true.

To solve this, we will follow these steps −

  • Define a method called getParent(), this will take character x and the map m, this will work as follows −

  • if m[x] = x, then return x,

  • otherwise set m[x] := getParent(m[x], m) and return m[x]

  • From the main method, do the following −

  • define two arrays equal and notEqual, create a map called parent

  • n := size of e

  • for i in range 0 to n – 1

    • set parent[e[i, 0]] := e[i, 0], parent[e[i, 3]] := e[i, 3]

    • if e[i, 1] is equal sign, then insert i into equal array, otherwise insert i into notEqual array

  • for i in range 0 to size of equal – 1

    • index := equal[i], set u, v as e[index, 0] and e[index, 3]

    • parent[getParent(u, parent)] := parent[getParent(v, parent)]

  • for i in range 0 to size of notEqual – 1

    • index := notEqual[i], set u, v as e[index, 0] and e[index, 3]

    • if getParent(u, parent) = getParent(v, parent), then return false

  • return true

Let us see the following implementation to get better understanding −


 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   char getParent(char x, map <char, char> m){
      if(m[x] == x) return x;
      return m[x] = getParent(m[x], m);
   bool equationsPossible(vector<string>& e) {
      vector <int> equal;
      vector <int> notEqual;
      map <char, char> parent;
      int n = e.size();
      for(int i = 0; i < n; i++){
         parent[e[i][0]]= e[i][0];
         parent[e[i][3]]= e[i][3];
         if(e[i][1] == '='){
      for(int i = 0; i < equal.size(); i++){
         int idx = equal[i];
         char u = e[idx][0];
         char v = e[idx][3];
         parent[getParent(u, parent)] = parent[getParent(v, parent)];
      for(int i = 0; i < notEqual.size(); i++){
         int idx = notEqual[i];
         char u = e[idx][0];
         char v = e[idx][3];
         if(getParent(u, parent) == getParent(v, parent)) return false;
      return true;
   vector<string> v1 = {"a==b","b==c","a==c"};
   Solution ob;
   cout << (ob.equationsPossible(v1));




Updated on 30-Apr-2020 14:08:53