All the variables in the equations are lower case English alphabets.
For Example:
You are given ‘equations’ = [‘a==b’, ‘a==c’, ‘b!=c’], here ‘a’ is equal to ‘b’ and ‘c’ so by associative law ‘b’, and ‘c’ must be equal, but it is given ‘b!=c’. Hence all the equations do not hold. Therefore the answer is False.
The first input line contains a single integer ‘T’, representing the number of test cases.
The first line of input contains ‘N’ representing the number of strings.
The following ‘N’ lines each contain a string representing a string in the equations array.
Output Format:
For each test case, print ‘True’ or ‘False’, representing if all the equations satisfy or not.
For each test case, print a separate line.
1 <= T <= 10
1 <= |equations| <= 10000
|equations[i]| = 4
Time Limit: 1 sec
Note:
You do not need to print anything. It has already been taken care of. Just implement the function.
2
3
a==b
a==c
a!=c
3
a==b
b==c
c==d
False
True
For the first test case, ‘equations’ = [‘a==b’, ‘a==c’, ‘b!=c’], here ‘a’ is equal to ‘b’ and ‘c’ so by associative law ‘b’, and ‘c’ must be equal, but it is given ‘b!=c’. Hence all the equations do not hold. Therefore the answer is False.
For the second test case, ‘equations’ = [‘a==b’, ‘b==c’, ‘c==d’], here ‘a’ is equal to ‘b’ and ‘b’ is equal to ‘c’, and ‘c’ is equal to ‘d’. Hence all the equations do hold. Therefore the answer is True.
2
2
a==b
b==b
2
a!=b
b!=a
True
True
Try to make a graph from the equations
In this approach, we will make a graph out of equations, we will add an edge between two nodes if there exists and the ‘==’ sign between them. This will make all the equal elements in the same components of the graph and all the unequal in different components.
The for each equation we have a ‘!=’ between nodes, we check using DFS if it’s possible to reach one node from the other.
We create a DFS(x, y, adj, visited), where y is the node from which we are checking if it’s possible to reach x, adj is the adjacency list of the graph we formed, and visited is the set of all the visited nodes.
Algorithm:
O(N^2), Where N is the number of equations.
We are iterating over each equation of the graph, which will cost O(N), then a DFS operation on a graph costs O(E + V); in this case, E = N and V is at most 26. Hence the time complexity for DFS is O(N), Hene the final time complexity is O(N^2).
O(1),
We are maintaining an adjacency list that will take O(1) space since we will have a maximum of 26 nodes. The space complexity of DFS will also be O(1). Hence the final space complexity is O(1).