Satisfiability of Equality Equations

Medium Graphs Connected Components Original on LeetCode

Reported atGoogle

Satisfiability of Equality Equations is a medium graphs problem solved with the connected components pattern. The best approach, optimal (union-find), runs in O(n · α(26)) time and O(26) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (graph search per inequality) up.

Problem

You get an array equations of strings, each exactly four characters long and shaped like "x==y" or "x!=y", where x and y are lowercase letters standing for integer variables (they may be the same letter).

Decide whether you can give each letter an integer value so that every equation holds at once. Return true if such an assignment exists and false otherwise.

Examples

Example 1

Input
equations = ["p==q", "q==r", "r!=p"]
Output
false
Why
p equals q and q equals r, so p must equal r, which breaks "r!=p".

Example 2

Input
equations = ["m==n", "n!=k", "k==j"]
Output
true
Why
Give m and n one value and k and j another; every equation holds.

Example 3

Input
equations = ["z!=z"]
Output
false
Why
No value differs from itself.

Constraints

  • 1 <= equations.length <= 500
  • equations[i].length == 4
  • equations[i][0] and equations[i][3] are lowercase letters.
  • equations[i][1..2] is either == or !=.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (graph search per inequality)O(n · (26 + n))O(26 + n)
Optimal (union-find)O(n · α(26))O(26)

1Brute force (graph search per inequality)

TimeO(n · (26 + n))Each of up to n inequalities may traverse the whole graph of 26 letters and up to n edges.
SpaceO(26 + n)Adjacency lists for the equality edges plus a visited array.

Build an undirected graph whose edges are the == equations. For every != equation, search the graph from one letter; if the other letter is reachable, the two must be equal and the system is impossible.

  1. For each "a==b", add the edge a - b.
  2. For each "a!=b", run a DFS from a over the equality edges.
  3. If b is visited (including a == b as letters), return false.
  4. If no inequality fails, return true.
class Solution {
    public boolean equationsPossible(String[] equations) {
        List<List<Integer>> adj = new ArrayList<>();
        for (int i = 0; i < 26; i++) adj.add(new ArrayList<>());
        for (String e : equations) {
            if (e.charAt(1) == '=') {
                int a = e.charAt(0) - 'a', b = e.charAt(3) - 'a';
                adj.get(a).add(b);
                adj.get(b).add(a);
            }
        }
        for (String e : equations) {
            if (e.charAt(1) == '!') {
                boolean[] seen = new boolean[26];
                dfs(e.charAt(0) - 'a', adj, seen);
                if (seen[e.charAt(3) - 'a']) return false;
            }
        }
        return true;
    }

    private void dfs(int u, List<List<Integer>> adj, boolean[] seen) {
        seen[u] = true;
        for (int v : adj.get(u)) {
            if (!seen[v]) dfs(v, adj, seen);
        }
    }
}

2Optimal (union-find)

TimeO(n · α(26))Two passes over the equations; each find with path compression is effectively constant.
SpaceO(26)One parent array of size 26.

Use a disjoint-set structure over the 26 letters. A first pass unions the two sides of every == equation. A second pass checks each != equation: if both sides have the same root, they were forced equal, so the system is impossible.

  1. parent[i] = i for the 26 letters.
  2. For each "a==b", union(a, b).
  3. For each "a!=b", if find(a) == find(b), return false.
  4. Return true.
class Solution {
    private final int[] parent = new int[26];

    public boolean equationsPossible(String[] equations) {
        for (int i = 0; i < 26; i++) parent[i] = i;
        for (String e : equations) {
            if (e.charAt(1) == '=') {
                parent[find(e.charAt(0) - 'a')] = find(e.charAt(3) - 'a');
            }
        }
        for (String e : equations) {
            if (e.charAt(1) == '!' && find(e.charAt(0) - 'a') == find(e.charAt(3) - 'a')) {
                return false;
            }
        }
        return true;
    }

    private int find(int x) {
        while (parent[x] != x) {
            parent[x] = parent[parent[x]];
            x = parent[x];
        }
        return x;
    }
}

Edge cases to test

  • A variable compared with itself: "a==a" is always fine, "a!=a" is always false
  • An inequality that appears before the equalities that break it
  • Long chains of equalities linking many letters
  • Only inequalities, which are always satisfiable unless one compares a letter with itself

Hints

Hint 1

Equalities group the letters: every letter in a group must share one value.

Hint 2

Once the groups are known, an inequality fails exactly when both of its letters are in the same group.

Hint 3

Process all the == equations first (union them), then check every != equation.

FAQ

What is the best time complexity for Satisfiability of Equality Equations?

Optimal (union-find) runs in O(n · α(26)) time and O(26) extra space. Two passes over the equations; each find with path compression is effectively constant.

Which pattern does Satisfiability of Equality Equations use?

It is a graphs problem that uses the connected components pattern. Other problems with the same pattern: Number of Provinces, Number of Islands, Evaluate Division.

Is there a brute force solution for Satisfiability of Equality Equations?

Yes. Brute force (graph search per inequality) takes O(n · (26 + n)) time and O(26 + n) space. Build an undirected graph whose edges are the == equations.

Which edge cases should I test for Satisfiability of Equality Equations?

A variable compared with itself: "a==a" is always fine, "a!=a" is always false; An inequality that appears before the equalities that break it; Long chains of equalities linking many letters; Only inequalities, which are always satisfiable unless one compares a letter with itself.