Satisfiability of Equality Equations
Decide whether equations like a==b and a!=c can all be true at once, by grouping the letters that must be equal.
Each string in the array equations==!="a==b""a!=b"
Example 1
Output: false
Example 2
Output: true
Example 3
Output: false
Explanation: a equals b and b equals c, so a must equal c.
The Idea
Think of the task as writing one number next to each letter. In Example 2, both equations ask for a and b to match, so writing 5 next to both works. Example 1 asks for a and b to match and also to differ, and no pair of numbers can do both.
Example 3 is less direct. No single equation mentions a and c together as equal. Yet "a==b""b==c""a!=c"
So the ==!=
Look at the picture below. On the left, each letter of Example 3 is a circle, and each ====
The dashed line, a!=c!=
The right side of the picture shows a compact way to remember the groups. Each letter stores one other letter of its group, called its parent. a's parent is b, b's parent is c, and c's parent is c itself, which makes c the group's root. To find a letter's group, follow the parents until you reach a root: from a, the walk goes a, b, c.
Two letters are in the same group exactly when their walks stop at the same root. Joining two groups needs a single change: make one root the parent of the other. This structure is called union-find, after its two operations: find a letter's root, and take the union of two groups.
That gives the whole plan. First build the groups from every ==!=
Solution Approach
Turning that plan into code means settling three things: how to store the parents, why the equations are read in two passes, and how to keep the walks to a root short. A graph search can find the same groups too, as an optional alternative.
Storing the parents
Where do the parents live? There are only 26 lowercase letters, so an int'a''c' - 'a'=!
At the start, every letter is its own parent, so there are 26 groups of one letter each. For "a==b"
Reading the equations in two passes
Why not judge each !===["a!=c", "a==b", "b==c"]"a!=c"
So the first pass reads every equation and handles only the ==!=
Keeping the walks short
How long can a walk to the root get? Joins can stack letters into one long chain, and every walk follows the chain to its end. A small trick shortens it: while walking up, point each letter at its grandparent, the parent of its parent. In the picture, a walk from a sets a's parent to c, so the next walk from a takes one step. Pointing each letter at its grandparent like this is called path halving.
With only 26 letters, a chain never gets longer than 26 steps, so path halving is a small improvement here. It matters for union-find over many items.
Optional: finding the groups with a graph search
The groups can also be found by walking the graph from the picture. Store it as an adjacency list: for each letter, the letters it shares an =="a==b"
Then start a depth-first search (DFS) from each letter that has no group number yet. DFS goes from a letter along one line as far as it can, then backs up and tries the next line, and gives every letter it reaches the same group number. The !=
Java Solution
The method equationsPossible
- First, create the array
with 26 entries and setparent , so each letter starts as the root of its own group.parent[i] = i - Pass 1: a loop reads every equation
. Whene ise.charAt(1) , it turns the two letters into indexes with'=' ande.charAt(0) - 'a' . It finds both roots with the helpere.charAt(3) - 'a' and makes the second root the parent of the first.find - The helper
follows parents in afind(parent, x) loop until it reaches a letter that is its own parent, and returns that root. On the way,while points each letter at its grandparent.parent[x] = parent[parent[x]] - Pass 2: a second loop reads the equations again. When
ise.charAt(1) and both letters have the same root, the method returns false at once.'!' - If the second loop finishes without a conflict, return true.
The main"a!=c"!=
import java.util.Arrays;
public class SatisfiabilityOfEqualityEquations {
public static boolean equationsPossible(String[] equations) {
int[] parent = new int[26];
for (int i = 0; i < 26; i++) {
parent[i] = i; // each letter starts as its own group
}
// Pass 1: every "==" puts its two letters in the same group.
for (String e : equations) {
if (e.charAt(1) == '=') {
parent[find(parent, e.charAt(0) - 'a')] = find(parent, e.charAt(3) - 'a');
}
}
// Pass 2: a "!=" fails if its two letters ended up in the same group.
for (String e : equations) {
if (e.charAt(1) == '!'
&& find(parent, e.charAt(0) - 'a') == find(parent, e.charAt(3) - 'a')) {
return false;
}
}
return true;
}
private static int find(int[] parent, int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]]; // skip to the grandparent on the way up
x = parent[x];
}
return x;
}
private static void run(String... equations) {
System.out.println(Arrays.toString(equations) + " -> " + equationsPossible(equations));
}
public static void main(String[] args) {
run("a==b", "b!=a");
run("b==a", "a==b");
run("a==b", "b==c", "a!=c");
run("a!=c", "a==b", "b==c");
run("a==b", "c==d", "a!=c");
run("a!=a");
run("c==c", "b==d", "x!=z");
}
}
Running it prints:
[a==b, b!=a] -> false
[b==a, a==b] -> true
[a==b, b==c, a!=c] -> false
[a!=c, a==b, b==c] -> false
[a==b, c==d, a!=c] -> true
[a!=a] -> false
[c==c, b==d, x!=z] -> true
The third line, [a==b, b==c, a!=c] -> false"a!=c"==
That order is where a single loop goes wrong. A version that checks each !=[a!=c, a==b, b==c] -> true"a!=c"
On the fifth line, "a==b""c==d""a!=c"[a!=a] -> false"c==c"
Complexity
The work is two passes over the equations, and every walk to a root stays inside an array of 26 letters.
- Time: O(n) for n equations, because each of the two passes reads every equation once, and each
follows at most 26 parent links.find - Space: O(1), because the only storage is the 26-entry
array, however many equations there are, andparent walks with afind loop, so no stack of calls builds up.while
Union-find also decides whether a set of edges forms a tree in