VOOZH about

URL: https://www.geeksforgeeks.org/dsa/equation-satisfiability-check/

⇱ Equation satisfiability check - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Equation satisfiability check

Last Updated : 23 Jul, 2025

Given an array arr[] of size N where each arr[i] is a string denoting an equation, the task is to return true if all the statements are satisfactory otherwise return false if any two equations contradict each other. An equation can be one of the two types below:

  • Type 1: "a != b", which denotes that a is not equal to b
  • Type 2: "a == b", which denotes that both a and b are equal

Note: The provided equations are transitive in nature (i.e. if "a==b" and "b==c", then "a==c"). 

Examples:

Input: N = 3, arr[] = ["a==b", "a==c", "b != c"]
Output: False
Explanation: Given "a == b" and "a == c", using the transitive property we get "b == c ", but arr[2] i.e. "b != c" contradicts that, so we print False.

Input: N = 2, arr = ["a == b", "b == a"]
Output: True
Explanation: Clearly arr[0] and arr[1] are same equations and there does not exists any contradicting equation, hence we print True.

Efficient Approach: Using Disjoint Set Union (DSU) to solve the equations efficiently.

Since the Equations follow the transitive property, we can use Union operation of DSU to put together all the equal equations in a single set, for example if we have {a==b, b==c, d==e} then we will have two sets i.e. {a,b,c} and {d,e} . We can process all the equations of type 2 first using DSU and finally check all the equation of type 1 and retrieve our answer as per the below two cases:

  • Case 1: if both the variables of type 1 equation belong to same set
    • return False
  • Case 2: if all the type1 equation does not follow Case1
    • return True

Follow the steps to solve the problem:

  • Firstly, initialize the DSU data structure, i.e. Find(), Union(), and parent[] array.
  • Make the parent of each character itself.
  • For each equation of type 2, merge the variables using the Union operation
  • Now for each equation of type 1, if the variables belong to the same disjoint set then return "False" else return "True".

Below is the implementation of the above algorithm:


Output
False

Time Complexity: O(N), where N is the number of equations
Auxiliary Space: O(26), for the parent array

Comment
Article Tags: