![]() |
VOOZH | about |
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:
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:
Below is the implementation of the above algorithm:
False
Time Complexity: O(N), where N is the number of equations
Auxiliary Space: O(26), for the parent array