Check if the given Binary Expressions are valid

Given n expressions of the type x = y and x != y where 1 ≤ x, y ≤ n, the task is to check whether the integers from 1 to n can be assigned to x and y such that all the equations are satisfied.

Examples:

Input: x[] = {1, 2, 3}, op[] = {“=”, “=”, “!=”}, y[] = {2, 3, 1}
Output: Invalid
If 1 = 2 and 2 = 3 then 3 must be equal to 1.

Input: x[] = {1, 2}, op[] = {“=”, “=”}, y[] = {2, 3}
Output: Valid

Approach: The idea is to use union find. For each statement check if there exists “=” sign then find the parent values for the two variables and union them using rank method. Now once union has been done for all the variables having “=” operator between them, start checking for “!=” operator, if this operator exists between any two variables whose parents are same then the expressions are invalid, else they are valid.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the parent of an integer
int findParent(int i, vector<int> parent)
{
    if (parent[i] == i)
        return i;
    return findParent(parent[i], parent);
}
  
// Find union for both the integers x and y
// using rank method
void findUnion(int x, int y, vector<int>& parent,
               vector<int>& rank)
{
    int xroot = findParent(x, parent);
    int yroot = findParent(y, parent);
  
    // Union using rank method
    if (xroot != yroot) {
        if (rank[xroot] > rank[yroot]) {
            parent[y] = x;
            rank[xroot]++;
        }
        else if (rank[x] < rank[y]) {
            parent[x] = y;
            rank[yroot]++;
        }
        else {
            parent[y] = x;
            rank[xroot]++;
        }
    }
}
  
// Function that returns true if
// the expression is invalid
bool isInvalid(vector<int> u, vector<int> v,
               vector<string> op, int n)
{
    // Vector to store parent values
    // of each integer
    vector<int> parent;
  
    // Vector to store rank
    // of each integer
    vector<int> rank;
  
    parent.push_back(-1);
    rank.push_back(-1);
  
    // Initialize parent values for
    // each of the integers
    for (int i = 1; i <= n; i++)
        parent.push_back(i);
  
    // Initialize rank values for
    // each of the integers
    for (int i = 1; i <= n; i++)
        rank.push_back(0);
  
    // Check for = operator and find union
    // for them
    for (int i = 0; i < n; i++)
        if (op[i] == "=")
            findUnion(u[i], v[i], parent, rank);
  
    // Check for != operator
    for (int i = 0; i < n; i++) {
        if (op[i] == "!=") {
            // If the expression is invalid
            if (findParent(u[i], parent)
                == findParent(v[i], parent))
                return true;
        }
    }
  
    // Expression is valid
    return false;
}
  
// Driver code
int main()
{
    vector<int> u;
    vector<int> v;
    vector<string> op;
  
    // Store the first integer
    u.push_back(1);
    u.push_back(2);
    u.push_back(3);
  
    // Store the second integer
    v.push_back(2);
    v.push_back(3);
    v.push_back(1);
  
    // Store the operators
    op.push_back("=");
    op.push_back("=");
    op.push_back("!=");
  
    // Number of expressions
    int n = u.size();
    if (isInvalid(u, v, op, n))
        cout << "Invalid";
    else
        cout << "Valid";
  
    return 0;
}

chevron_right


Python3

# Python3 implementation of the approach

# Function to return the parent of an integer
def findParent(i, parent):

if parent[i] == i:
return i
return findParent(parent[i], parent)

# Find union for both the integers
# x and y using rank method
def findUnion(x, y, parent, rank):

xroot = findParent(x, parent)
yroot = findParent(y, parent)

# Union using rank method
if xroot != yroot:
if rank[xroot] > rank[yroot]:
parent[y] = x
rank[xroot] += 1

elif rank[x] < rank[y]: parent[x] = y rank[yroot] += 1 else: parent[y] = x rank[xroot] += 1 # Function that returns true if # the expression is invalid def isInvalid(u, v, op, n): # Vector to store parent values # of each integer parent = [] # Vector to store rank # of each integer rank = [] parent.append(-1) rank.append(-1) # Initialize parent values for # each of the integers for i in range(1, n + 1): parent.append(i) # Initialize rank values for # each of the integers for i in range(1, n + 1): rank.append(0) # Check for = operator and # find union for them for i in range(0, n): if op[i] == "=": findUnion(u[i], v[i], parent, rank) # Check for != operator for i in range(0, n): if op[i] == "!=": # If the expression is invalid if (findParent(u[i], parent) == findParent(v[i], parent)): return True # Expression is valid return False # Driver code if __name__ == "__main__": u = [1, 2, 3] v = [2, 3, 1] op = ["=", "=", "!="] # Number of expressions n = len(u) if isInvalid(u, v, op, n): print("Invalid") else: print("Valid") # This code is contributed by Rituraj Jain [tabbyending]

Output:

Invalid


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 : rituraj_jain