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 has four characters: a lowercase letter, then == or !=, then another lowercase letter. Each letter is a variable, so "a==b" says a and b are equal and "a!=b" says they are different. Return true if you can give every variable an integer value so that all the equations hold at the same time, and false otherwise.

Example 1
Input: equations = ["a==b", "b!=a"]
Output: false
Example 2
Input: equations = ["b==a", "a==b"]
Output: true
Example 3
Input: equations = ["a==b", "b==c", "a!=c"]
Output: false
Explanation: a equals b and b equals c, so a must equal c.
Solution

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" gives a and b the same number, and "b==c" gives c that number too. So a, b and c all carry one number, and "a!=c" asks two of them to differ, which cannot happen.

So the == equations sort the letters into groups whose members must all be equal, and equality carries along a chain of them. That raises two questions. How do we tell whether two letters ended up in the same group, when the chain linking them can be long? And when is it safe to judge a != equation?

Look at the picture below. On the left, each letter of Example 3 is a circle, and each == equation is a solid line between two circles. Letters joined by a path of solid lines, here a, b and c, form one group. Circles joined by lines like this make a graph: the letters are its vertices, the == equations are its edges, and a group is everything you can reach along the lines.

Left: the letters a, b and c of Example 3 as circles. Solid lines a==b and b==c join them into one group: a, b, c. A dashed line a!=c joins two letters of that group. Right: after the == equations, a's parent is b, b's parent is c, and c is the root because its parent is itself. find(a) follows a, b, c and stops at c, find(c) is c, so a!=c fails.

The dashed line, a!=c, joins two letters of the box labelled "one group: a, b, c". That is the conflict. If a != line ran between two different groups, there would be no problem: give each group its own number.

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 == equation. Then, for each != equation, compare the roots of its two letters: the same root means the answer is false. If none of them fails, one number per group makes every equation true.

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 array of 26 entries is enough, with a at index 0 and z at index 25. Subtracting 'a' from a letter gives its index, since 'c' - 'a' is 2. The two letters of an equation sit at positions 0 and 3 of the string, and position 1 holds = or !.

At the start, every letter is its own parent, so there are 26 groups of one letter each. For "a==b", find the root of a and the root of b, and make the root of b the parent of the root of a.

Reading the equations in two passes

Why not judge each != as soon as it is read? Because an == further down the list can still join its two letters. Take Example 3 in a different order: ["a!=c", "a==b", "b==c"]. When "a!=c" is read first, a and c are still in separate groups, so the check passes, and the two later equations then put them together.

So the first pass reads every equation and handles only the == ones. Once the groups are final, the second pass reads the list again and checks only the != ones.

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 == line with. For Example 3 that is a: [b], b: [a, c], c: [b], built by adding b to a's list and a to b's list for "a==b", and so on.

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 != check then compares group numbers. It gives the same answers, but needs the lists, while union-find needs one small array.

Java Solution

The method equationsPossible works in these steps:

  1. First, create the array parent with 26 entries and set parent[i] = i, so each letter starts as the root of its own group.
  2. Pass 1: a loop reads every equation e. When e.charAt(1) is '=', it turns the two letters into indexes with e.charAt(0) - 'a' and e.charAt(3) - 'a'. It finds both roots with the helper find and makes the second root the parent of the first.
  3. The helper find(parent, x) follows parents in a while loop until it reaches a letter that is its own parent, and returns that root. On the way, parent[x] = parent[parent[x]] points each letter at its grandparent.
  4. Pass 2: a second loop reads the equations again. When e.charAt(1) is '!' and both letters have the same root, the method returns false at once.
  5. If the second loop finishes without a conflict, return true.

The main method runs the three examples, Example 3 with "a!=c" moved to the front, two groups kept apart by a !=, a letter that must differ from itself, and letters that are never joined.

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

Output
[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, is Example 3: after pass 1, a, b and c all have the root c, as in the picture. The fourth line reads the same equations with "a!=c" first and still prints false, because pass 2 starts only after every == is in.

That order is where a single loop goes wrong. A version that checks each != as soon as it reads it prints [a!=c, a==b, b==c] -> true for this input, since a and c are still apart when "a!=c" comes up.

On the fifth line, "a==b" and "c==d" make two groups, and "a!=c" compares two different roots, so the result is true: give a and b the number 1, and c and d the number 2. [a!=a] -> false shows that a letter always shares a root with itself. On the last line, "c==c" joins c to its own group, which changes nothing, and x and z are never joined, so the result is true.

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 find follows at most 26 parent links.
  • Space: O(1), because the only storage is the 26-entry parent array, however many equations there are, and find walks with a while loop, so no stack of calls builds up.

Union-find also decides whether a set of edges forms a tree in Graph Valid Tree.